aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/VSIX/Tango.BuildExtensions/TangoBuildCommand.cs
blob: 36506e5b04a339753a09ca4c1a115f6c8bc7bf5c (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
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
//------------------------------------------------------------------------------
// <copyright file="TangoBuildCommand.cs" company="Company">
//     Copyright (c) Company.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

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;

namespace Tango.BuildExtensions
{
    /// <summary>
    /// Command handler
    /// </summary>
    internal sealed class TangoBuildCommand
    {
        private DTE2 _dte;
        private IList<Project> _projects;
        private SelectForm _form;
        private TestStack.White.Application _application;
        private TestStack.White.UIItems.WindowItems.Window _window;
        private System.Diagnostics.Process _vsProcess;

        private const String dalProjectName = "Tango.DAL.Remote";
        private const String edmxModelName = "RemoteADO.edmx";
        private const String observablesGeneratorProjectName = "Tango.DBObservablesGenerator.CLI";
        private const String observablesProjectName = "Tango.BL";
        private const String pmrGeneratorProjectName = "Tango.PMRGenerator.CLI";
        private const String pmrProjectName = "Tango.PMR";
        private const String protoCliProjectName = "Tango.Protobuf.CLI";

        #region Redundant

        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 0x0100;

        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("c03a7b01-8109-4ec5-8f90-858bed027e5d");

        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly Package package;

        /// <summary>
        /// Initializes a new instance of the <see cref="TangoBuildCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private TangoBuildCommand(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            this.package = package;

            OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (commandService != null)
            {
                var menuCommandID = new CommandID(CommandSet, CommandId);
                var menuItem = new MenuCommand(this.MenuItemCallback, menuCommandID);
                commandService.AddCommand(menuItem);
            }
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static TangoBuildCommand Instance
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private IServiceProvider ServiceProvider
        {
            get
            {
                return this.package;
            }
        }

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        public static void Initialize(Package package)
        {
            Instance = new TangoBuildCommand(package);
        }

        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            Start();
        }

        #endregion

        #region Main

        private void Start()
        {
            _form = null;

            BuildForm buildForm = new BuildForm();
            if (buildForm.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                _projects = Projects().ToList();

                String vsWindowTitle = _dte.DTE.MainWindow.Caption;
                _vsProcess = System.Diagnostics.Process.GetProcesses().ToList().SingleOrDefault(x => x.MainWindowTitle == vsWindowTitle);
                _application = TestStack.White.Application.Attach(_vsProcess);
                _window = _application.GetWindow(vsWindowTitle);

                OpenProgressForm();

                try
                {
                    if (buildForm.UpdateDataBaseEntities)
                    {
                        UpdateDatabaseEntities();
                    }
                    if (buildForm.GenerateAndBuildObservables)
                    {
                        GenerateAndBuildObservables();
                    }
                    if (buildForm.GenerateAutoPmrMessages)
                    {
                        GenerateAutoPMRMessages();
                    }
                    if (buildForm.UpdateAndBuildPmrMessages)
                    {
                        UpdateAndBuildPmrMessages();
                    }
                    if (buildForm.BuildSolution)
                    {
                        BuildSolution();
                    }

                    SetStatusText("Done!");
                    Wait(1000);
                    CloseProgressForm();
                }
                catch (Exception ex)
                {
                    CloseProgressForm();
                    ShowMessage(ex.Message);
                }
            });
        }

        private void UpdateDatabaseEntities()
        {
            var project = _projects.SingleOrDefault(x => x.Name == dalProjectName);

            if (project == null)
            {
                throw new NullReferenceException("Could not find the Tango solution!");
            }

            var projectItems = project.ProjectItems.OfType<ProjectItem>().ToList();

            SetStatusText("Locating " + edmxModelName + " scheme...");

            var items = GetProjectItemsDeep(project);

            var edmx = GetProjectItemsDeep(project).SingleOrDefault(x => x.Name == edmxModelName);

            if (edmx == null)
            {
                throw new NullReferenceException("Could not locate " + edmxModelName + "!");
            }

            SetStatusText("Expanding diagram...");

            edmx.ExpandView();

            SetStatusText("Opening edmx diagram window...");

            Window win = edmx.Open(EnvDTE.Constants.vsViewKindPrimary);
            win.Visible = true;

            SetStatusText("Waiting for edmx diagram window...");

            _window.WaitTill(() => _window.Get(SearchCriteria.ByText(edmxModelName + " [Diagram1]")) != null);

            SetStatusText("Cleaning up edmx scheme...");

            _dte.MainWindow.Activate();
            _dte.ExecuteCommand("Edit.SelectAll");
            Keyboard.Instance.PressSpecialKey(KeyboardInput.SpecialKeys.DELETE);
            WaitForWindowOpen("Delete Unmapped Tables and Views").PressKey(KeyboardInput.SpecialKeys.RETURN);
            WaitForWindowClose("Delete Unmapped Tables and Views");

            _window.WaitWhileBusy();

            SetStatusText("Reinitializing edmx scheme...");

            var window = WindowInfo.GetWindow(edmxModelName + " [Diagram1]*");
            window.SetActive();

            Keyboard.Instance.HoldKey(KeyboardInput.SpecialKeys.SHIFT);
            Keyboard.Instance.PressSpecialKey(KeyboardInput.SpecialKeys.F10);
            Keyboard.Instance.LeaveAllKeys();

            Wait(100);

            for (int i = 0; i < 7; i++)
            {
                Keyboard.Instance.PressSpecialKey(KeyboardInput.SpecialKeys.DOWN);
                Wait(10);
            }

            Keyboard.Instance.PressSpecialKey(KeyboardInput.SpecialKeys.RETURN);

            var updateWindow = WaitForWindowOpen("Update Wizard");

            _window.WaitWhileBusy();

            Wait(1000);

            updateWindow.PressKey(KeyboardInput.SpecialKeys.SPACE);

            Wait(50);

            updateWindow.PressKey(KeyboardInput.SpecialKeys.RETURN);

            SetStatusText("Generating edmx scheme...");

            WaitForWindowClose("Update Wizard");

            _window.WaitWhileBusy();

            SetStatusText("Saving changes...");

            win.Close(vsSaveChanges.vsSaveChangesYes);

            _window.WaitWhileBusy();

            foreach (var template in edmx.ProjectItems.OfType<ProjectItem>().Where(x => x.Name.EndsWith(".tt")))
            {
                SetStatusText("Running custom tool for " + template.Name + "...");
                (template.Object as VSProjectItem).RunCustomTool();
                _window.WaitWhileBusy();
            }

            _window.WaitWhileBusy();

            SetStatusText("Building project " + dalProjectName + "...");

            _dte.Solution.SolutionBuild.BuildProject("Debug", project.FullName, true);

            if (_dte.Solution.SolutionBuild.LastBuildInfo > 0)
            {
                throw new ExternalException(dalProjectName + " failed to build!");
            }
        }

        private void GenerateAndBuildObservables()
        {
            var project = _projects.SingleOrDefault(x => x.Name == observablesGeneratorProjectName);

            if (project == null)
            {
                throw new NullReferenceException("Could not locate project " + observablesGeneratorProjectName);
            }

            SetStatusText("Building project " + observablesGeneratorProjectName + "...");

            _dte.Solution.SolutionBuild.BuildProject("Debug", project.FullName, true);

            _dte.Solution.Properties.Item("StartupProject").Value = observablesGeneratorProjectName;

            SetStatusText("Executing observables generator...");

            _dte.ExecuteCommand("Debug.Start");

            WaitForWindowOpen("Tango Observables Generator");

            WaitForWindowClose("Tango Observables Generator");

            var observablesProject = _projects.SingleOrDefault(x => x.Name == observablesProjectName);

            if (observablesProject == null)
            {
                throw new NullReferenceException("Could not locate project " + observablesProjectName);
            }

            SetStatusText("Updating " + observablesProjectName + "...");

            foreach (var file in Directory.GetFiles(Path.GetDirectoryName(observablesProject.FileName), "*.cs", SearchOption.AllDirectories))
            {
                String parentFolderName = Path.GetFileName(Path.GetDirectoryName(file));

                if (parentFolderName != "Debug" && parentFolderName != "Release" && parentFolderName != "obj")
                {
                    SetStatusText("Adding/Updating file " + Path.GetFileName(file) + "...");
                    observablesProject.ProjectItems.AddFromFile(file);
                    Wait(10);
                }
            }

            SetStatusText("Building project " + observablesProjectName + "...");

            _dte.Solution.SolutionBuild.BuildProject("Debug", observablesProject.FullName, true);

            if (_dte.Solution.SolutionBuild.LastBuildInfo > 0)
            {
                throw new ExternalException(observablesProjectName + " failed to build!");
            }
        }

        private void GenerateAutoPMRMessages()
        {
            var project = _projects.SingleOrDefault(x => x.Name == pmrGeneratorProjectName);

            if (project == null)
            {
                throw new NullReferenceException("Could not locate project " + pmrGeneratorProjectName);
            }

            SetStatusText("Building project " + pmrGeneratorProjectName + "...");

            _dte.Solution.SolutionBuild.BuildProject("Debug", project.FullName, true);

            _dte.Solution.Properties.Item("StartupProject").Value = pmrGeneratorProjectName;

            SetStatusText("Executing PMR generator...");

            _dte.ExecuteCommand("Debug.Start");

            WaitForWindowOpen("Tango PMR Generator");

            WaitForWindowClose("Tango PMR Generator");
        }

        private void UpdateAndBuildPmrMessages()
        {
            var protoProject = _projects.SingleOrDefault(x => x.Name == protoCliProjectName);

            if (protoProject == null)
            {
                throw new NullReferenceException("Could not locate project " + protoCliProjectName);
            }

            SetStatusText("Building project " + protoCliProjectName + "...");

            _dte.Solution.SolutionBuild.BuildProject("Debug", protoProject.FullName, true);

            if (_dte.Solution.SolutionBuild.LastBuildInfo > 0)
            {
                throw new ExternalException(protoCliProjectName + " failed to build!");
            }

            _dte.Solution.Properties.Item("StartupProject").Value = protoCliProjectName;

            SetStatusText("Executing Tango Proto Compiler...");

            _dte.ExecuteCommand("Debug.Start");

            WaitForWindowOpen("Tango Protobuf Compiler");

            WaitForWindowClose("Tango Protobuf Compiler");


            var project = _projects.SingleOrDefault(x => x.Name == pmrProjectName);

            if (project == null)
            {
                throw new NullReferenceException("Could not locate project " + pmrProjectName);
            }

            SetStatusText("Updating " + pmrProjectName + "...");

            foreach (var file in Directory.GetFiles(Path.GetDirectoryName(project.FileName), "*.cs", SearchOption.AllDirectories))
            {
                String parentFolderName = Path.GetFileName(Path.GetDirectoryName(file));

                if (parentFolderName != "Debug" && parentFolderName != "Release" && parentFolderName != "obj")
                {
                    SetStatusText("Adding/Updating file " + Path.GetFileName(file) + "...");
                    project.ProjectItems.AddFromFile(file);
                    Wait(10);
                }
            }

            SetStatusText("Building project " + pmrProjectName + "...");

            _dte.Solution.SolutionBuild.BuildProject("Debug", project.FullName, true);

            if (_dte.Solution.SolutionBuild.LastBuildInfo > 0)
            {
                throw new ExternalException(pmrProjectName + " failed to build!");
            }
        }

        private void BuildSolution()
        {
            SetStatusText("Building solution...");
            _dte.Solution.SolutionBuild.Build(true);

            if (_dte.Solution.SolutionBuild.LastBuildInfo > 0)
            {
                throw new ExternalException("Error building solution!");
            }
        }

        #endregion

        #region Solution & Projects

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

        public IList<Project> Projects()
        {
            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;
        }

        private List<ProjectItem> GetProjectItemsDeep(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);
                }
            }
        }

        #endregion

        #region Notifications

        private void WriteToConsole(String text)
        {
            // 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);
        }

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

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

        #endregion

        #region Windows API

        private 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;
        }

        private 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

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

        #endregion

        #region Status Form

        private void OpenProgressForm()
        {
            System.Threading.Thread thread = new System.Threading.Thread(() =>
            {
                _form = new SelectForm();
                var handle = _form.Handle;
                _form.ShowDialog();
            });

            thread.SetApartmentState(System.Threading.ApartmentState.STA);
            thread.Start();

            while (_form == null || !_form.IsHandleCreated) { }
        }

        private void SetStatusText(String text)
        {
            _form.Invoke(new Action(() =>
            {
                _form.SetStatus(text);
            }));
        }

        private void CloseProgressForm()
        {
            _form.Invoke(new Action(() =>
            {
                _form.Close();
                _form = null;
            }));
        }

        #endregion
    }
}