aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/VSIX/Tango.BuildExtensions/VSIXBase.cs
blob: 349962280766b1731a9809a34611f4f340673ff4 (plain)
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
using System;
using System.ComponentModel.Design;
using System.Globalization;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.Collections.Generic;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using System.Linq;
using TestStack.White.UIItems.Finders;
using TestStack.White.InputDevices;
using TestStack.White.UIItems;
using VSLangProj;
using System.Runtime.InteropServices;
using TestStack.White.WindowsAPI;
using System.IO;
using Microsoft.VisualStudio.Threading;

namespace Tango.BuildExtensions
{
    public class VSIXBase
    {
        private IVsThreadedWaitDialog2 _vsProgress = null;

        public IServiceProvider BaseServiceProvider { get; private set; }

        public DTE2 DTE { get; private set; }

        public VSIXBase(IServiceProvider serviceProvider)
        {
            BaseServiceProvider = serviceProvider;
            DTE = GetActiveIDE();
        }

        #region Solution & Projects

        private DTE2 GetActiveIDE()
        {
            // Get an instance of currently running Visual Studio IDE.
            DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;
            return dte2;
        }

        public IList<Project> GetSolutionProjects()
        {
            Projects projects = GetActiveIDE().Solution.Projects;
            List<Project> list = new List<Project>();
            var item = projects.GetEnumerator();
            while (item.MoveNext())
            {
                var project = item.Current as Project;
                if (project == null)
                {
                    continue;
                }

                if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
                {
                    list.AddRange(GetSolutionFolderProjects(project));
                }
                else
                {
                    list.Add(project);
                }
            }

            return list;
        }

        private IEnumerable<Project> GetSolutionFolderProjects(Project solutionFolder)
        {
            List<Project> list = new List<Project>();
            for (var i = 1; i <= solutionFolder.ProjectItems.Count; i++)
            {
                var subProject = solutionFolder.ProjectItems.Item(i).SubProject;
                if (subProject == null)
                {
                    continue;
                }

                // If this is another solution folder, do a recursive call, otherwise add
                if (subProject.Kind == ProjectKinds.vsProjectKindSolutionFolder)
                {
                    list.AddRange(GetSolutionFolderProjects(subProject));
                }
                else
                {
                    list.Add(subProject);
                }
            }
            return list;
        }

        public List<ProjectItem> GetProjectItems(Project project)
        {
            List<ProjectItem> results = new List<ProjectItem>();
            FillProjectItems(project.ProjectItems.OfType<ProjectItem>().ToList(), results);
            return results;
        }

        private void FillProjectItems(List<ProjectItem> rootItems, List<ProjectItem> results)
        {
            foreach (var item in rootItems)
            {
                results.Add(item);

                if (item.ProjectItems.Count > 0)
                {
                    FillProjectItems(item.ProjectItems.OfType<ProjectItem>().ToList(), results);
                }
            }
        }

        protected String GetProjectOutputFilePath(EnvDTE.Project vsProject)
        {
            string fullPath = vsProject.Properties.Item("FullPath").Value.ToString();

            string outputPath = vsProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();

            string outputDir = Path.Combine(fullPath, outputPath);

            string outputFileName = vsProject.Properties.Item("OutputFileName").Value.ToString();

            string assemblyPath = Path.Combine(outputDir, outputFileName);

            return assemblyPath;
        }

        protected void SelectSolutionExplorerNode(string nodePath)
        {
            EnvDTE.UIHierarchyItem item;

            try
            {
                item = DTE.ToolWindows.SolutionExplorer.GetItem(nodePath);
                item.Select(vsUISelectionType.vsUISelectionTypeSelect);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
        }

        protected void ExpandSolutionExplorerNode(string nodePath)
        {
            EnvDTE.UIHierarchyItem item;

            try
            {
                var explorer = DTE.ToolWindows.SolutionExplorer;

                item = explorer.GetItem(nodePath);
                item.Select(vsUISelectionType.vsUISelectionTypeSelect);

                if (!item.UIHierarchyItems.Expanded)
                {
                    explorer.DoDefaultAction();
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
        }

        #endregion

        #region Notifications

        public void WriteToConsole(String text)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            // Get the output window
            var outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;

            // Ensure that the desired pane is visible
            var paneGuid = Microsoft.VisualStudio.VSConstants.OutputWindowPaneGuid.GeneralPane_guid;
            IVsOutputWindowPane pane;
            outputWindow.CreatePane(paneGuid, "General", 1, 0);
            outputWindow.GetPane(paneGuid, out pane);

            // Output the message
            pane.OutputString(text + Environment.NewLine);
        }

        public void ShowMessage(String text)
        {
            // Show a message box to prove we were here

            VsShellUtilities.ShowMessageBox(
                            BaseServiceProvider,
                            text,
                            "Tango",
                            OLEMSGICON.OLEMSGICON_INFO,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
        }

        #endregion

        #region Windows API

        protected WindowInfo WaitForWindowOpen(String title)
        {
            WindowInfo window = null;

            do
            {
                window = WindowInfo.GetAllWindows().SelectMany(x => x.Children).FirstOrDefault(x => x.Caption == title);
            } while (window == null);

            return window;
        }

        protected void WaitForWindowClose(String title)
        {
            while (WindowInfo.GetAllWindows().SelectMany(x => x.Children).ToList().Exists(x => x.Caption == title))
            {
                System.Threading.Thread.Sleep(100);
            }
        }

        #endregion

        #region Threading

        protected void Wait(int milli)
        {
            System.Threading.Thread.Sleep(milli);
        }

        #endregion

        #region Status Form

        protected void OpenVSProgress(String title, String message, bool intermediate)
        {
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
            ThreadHelper.Generic.Invoke(() =>
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
            {
                _vsProgress = null;
                ThreadHelper.ThrowIfNotOnUIThread();
                IVsThreadedWaitDialogFactory dialogFactory = BaseServiceProvider.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;
                dialogFactory.CreateInstance(out _vsProgress);


                if (intermediate)
                {
                    _vsProgress.StartWaitDialog(title, message, "", null, null, 0, false, true);
                }
                else
                {
                    _vsProgress.StartWaitDialogWithPercentageProgress(title, message, "", null, null, false, 0, 0, 100);
                }
            });
        }



        protected void SetVSProgress(String message, String progressText = null, int current = 0, int total = 0)
        {
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
            ThreadHelper.Generic.Invoke(() =>
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                bool c;
                _vsProgress.UpdateProgress(message, progressText, null, current, total, true, out c);
            });
        }

        protected void CloseVSProgress()
        {
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
            ThreadHelper.Generic.Invoke(() =>
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
            {
                _vsProgress.EndWaitDialog();
            });
        }

        #endregion

        #region Content

        protected string GetFullPathToContentFile(String fileName)
        {
            return Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase), fileName).Replace("file:\\", "");
        }

        #endregion

        #region IO

        /// <summary>
        /// Copies the specified directory source path to the specified destination.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <param name="destinationPath">The destination path.</param>
        /// <param name="copySubDirs">if set to <c>true</c> will copy sub directories.</param>
        /// <exception cref="DirectoryNotFoundException">Source directory does not exist or could not be found: "
        ///                     + sourcePath</exception>
        protected void CopyDirectory(string sourcePath, string destinationPath, bool copySubDirs, Action<String> progress = null)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourcePath);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sourcePath);
            }

            DirectoryInfo[] dirs = dir.GetDirectories();
            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(destinationPath))
            {
                Directory.CreateDirectory(destinationPath);
            }

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(destinationPath, file.Name);
                progress?.Invoke(temppath);
                file.CopyTo(temppath, true);
            }

            // If copying subdirectories, copy them and their contents to new location.
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destinationPath, subdir.Name);
                    CopyDirectory(subdir.FullName, temppath, copySubDirs);
                }
            }
        }

        #endregion
    }
}