aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Native
ModeNameSize
d---------Tango.ColorLib485logstatsplain
d---------Tango.Emulations.Native401logstatsplain
d---------Tango.ProtoTest267logstatsplain
d---------Tester348logstatsplain
//------------------------------------------------------------------------------
// <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 : VSIXBase
    {
        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) : base(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 = GetSolutionProjects().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();
                    }

                    SetProgressText("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();

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

            var items = GetProjectItems(project);

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

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

            SetProgressText("Expanding diagram...");

            edmx.ExpandView();

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

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

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

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

            SetProgressText("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();

            SetProgressText("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);

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

            WaitForWindowClose("Update Wizard");

            _window.WaitWhileBusy();

            SetProgressText("Saving changes...");

            win.Close(vsSaveChanges.vsSaveChangesYes);

            _window.WaitWhileBusy();

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

            _window.WaitWhileBusy();

            SetProgressText("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);
            }

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

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

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

            SetProgressText("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);
            }

            SetProgressText("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")
                {
                    SetProgressText("Adding/Updating file " + Path.GetFileName(file) + "...");
                    observablesProject.ProjectItems.AddFromFile(file);
                    Wait(10);
                }
            }

            SetProgressText("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);
            }

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

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

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

            SetProgressText("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);
            }

            SetProgressText("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;

            SetProgressText("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);
            }

            SetProgressText("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")
                {
                    SetProgressText("Adding/Updating file " + Path.GetFileName(file) + "...");
                    project.ProjectItems.AddFromFile(file);
                    Wait(10);
                }
            }

            SetProgressText("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()
        {
            SetProgressText("Building solution...");
            DTE.Solution.SolutionBuild.Build(true);

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

        #endregion
    }
}