Esempio n. 1
0
        private void LoadDevelopmentToolsEnvironment(string visualStudioVersion)
        {
            /* Make sure the DTE loads with the same version of Visual Studio as the
             * TwinCAT project was created in
             */
            string VisualStudioProgId = "VisualStudio.DTE." + visualStudioVersion;

            type = System.Type.GetTypeFromProgID(VisualStudioProgId);
            log.Info("Loading the Visual Studio Development Tools Environment (DTE)...");
            dte             = (EnvDTE80.DTE2)System.Activator.CreateInstance(type);
            dte.UserControl = false; // have devenv.exe automatically close when launched using automation
            dte.SuppressUI  = true;
            dte.ToolWindows.ErrorList.ShowErrors   = true;
            dte.ToolWindows.ErrorList.ShowMessages = true;
            dte.ToolWindows.ErrorList.ShowWarnings = true;
            var tcAutomationSettings = dte.GetObject("TcAutomationSettings");

            tcAutomationSettings.SilentMode = true;
            // Uncomment this if you want to run a specific version of TwinCAT
            ITcRemoteManager remoteManager = dte.GetObject("TcRemoteManager");

            remoteManager.Version = "3.1.4022.30";
        }
        static int Main(string[] args)
        {
            bool showHelp = false;

            OptionSet options = new OptionSet()
                                .Add("v=|VisualStudioSolutionFilePath=", v => VisualStudioSolutionFilePath = v)
                                .Add("t=|TwinCATProjectFilePath=", t => TwinCATProjectFilePath             = t)
                                .Add("?|h|help", h => showHelp = h != null);

            try {
                options.Parse(args);
            }
            catch (OptionException e) {
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `TcStaticAnalysisLoader --help' for more information.");
                return(Constants.RETURN_ERROR);
            }
            options.Parse(args);

            Console.WriteLine("TcStaticAnalysisLoader.exe : argument 1: " + VisualStudioSolutionFilePath);
            Console.WriteLine("TcStaticAnalysisLoader.exe : argument 2: " + TwinCATProjectFilePath);

            /* Make sure the user has supplied the paths for both the Visual Studio solution file
             * and the TwinCAT project file. Also verify that these two files exists.
             */
            if (showHelp || VisualStudioSolutionFilePath == null || TwinCATProjectFilePath == null)
            {
                DisplayHelp(options);
                return(Constants.RETURN_ERROR);
            }
            if (!File.Exists(VisualStudioSolutionFilePath))
            {
                Console.WriteLine("ERROR: Visual studio solution " + VisualStudioSolutionFilePath + " does not exist!");
                return(Constants.RETURN_ERROR);
            }
            if (!File.Exists(TwinCATProjectFilePath))
            {
                Console.WriteLine("ERROR : TwinCAT project file " + TwinCATProjectFilePath + " does not exist!");
                return(Constants.RETURN_ERROR);
            }


            /* Find visual studio version */
            string vsVersion = "";
            string line;
            bool   foundVsVersionLine = false;

            System.IO.StreamReader file = new System.IO.StreamReader(@VisualStudioSolutionFilePath);
            while ((line = file.ReadLine()) != null)
            {
                if (line.StartsWith("VisualStudioVersion"))
                {
                    string version = line.Substring(line.LastIndexOf('=') + 2);
                    Console.WriteLine("In Visual Studio solution file, found visual studio version " + version);
                    string[] numbers = version.Split('.');
                    string   major   = numbers[0];
                    string   minor   = numbers[1];

                    bool isNumericMajor = int.TryParse(major, out int n);
                    bool isNumericMinor = int.TryParse(minor, out int n2);

                    if (isNumericMajor && isNumericMinor)
                    {
                        vsVersion          = major + "." + minor;
                        foundVsVersionLine = true;
                    }
                    break;
                }
            }
            file.Close();

            if (!foundVsVersionLine)
            {
                Console.WriteLine("Did not find Visual studio version in Visual studio solution file");
                return(Constants.RETURN_ERROR);
            }

            /* Find TwinCAT project version */
            string tcVersion          = "";
            bool   foundTcVersionLine = false;

            file = new System.IO.StreamReader(@TwinCATProjectFilePath);
            while ((line = file.ReadLine()) != null)
            {
                if (line.Contains("TcVersion"))
                {
                    string version = line.Substring(line.LastIndexOf("TcVersion=\""));
                    int    pFrom   = version.IndexOf("TcVersion=\"") + "TcVersion=\"".Length;
                    int    pTo     = version.LastIndexOf("\">");
                    if (pTo > pFrom)
                    {
                        tcVersion          = version.Substring(pFrom, pTo - pFrom);
                        foundTcVersionLine = true;
                        Console.WriteLine("In TwinCAT project file, found version " + tcVersion);
                    }
                    break;
                }
            }
            file.Close();
            if (!foundTcVersionLine)
            {
                Console.WriteLine("Did not find TcVersion in TwinCAT project file");
                return(Constants.RETURN_ERROR);
            }


            /* Make sure TwinCAT version is at minimum version 3.1.4022.0 as the static code
             * analysis tool is only supported from this version and onward
             */
            var versionMin      = new Version(Constants.MIN_TC_VERSION_FOR_SC_ANALYSIS);
            var versionDetected = new Version(tcVersion);
            var compareResult   = versionDetected.CompareTo(versionMin);

            if (compareResult < 0)
            {
                Console.WriteLine("The detected TwinCAT version in the project does not support TE1200 static code analysis");
                Console.WriteLine("The minimum version that supports TE1200 is " + Constants.MIN_TC_VERSION_FOR_SC_ANALYSIS);
                return(Constants.RETURN_ERROR);
            }

            MessageFilter.Register();

            /* Make sure the DTE loads with the same version of Visual Studio as the
             * TwinCAT project was created in
             */
            string VisualStudioProgId = "VisualStudio.DTE." + vsVersion;
            Type   type = System.Type.GetTypeFromProgID(VisualStudioProgId);

            EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)System.Activator.CreateInstance(type);

            dte.SuppressUI         = true;
            dte.MainWindow.Visible = false;
            EnvDTE.Solution visualStudioSolution = dte.Solution;
            visualStudioSolution.Open(@VisualStudioSolutionFilePath);
            EnvDTE.Project pro = visualStudioSolution.Projects.Item(1);

            ITcRemoteManager remoteManager = dte.GetObject("TcRemoteManager");

            remoteManager.Version = tcVersion;
            var settings = dte.GetObject("TcAutomationSettings");

            settings.SilentMode = true; // Only available from TC3.1.4020.0 and above

            /* Build the solution and collect any eventual errors. Make sure to
             * filter out everything that is
             * - Either a warning or an error
             * - Starts with the string "SA", which is everything from the TE1200
             *   static code analysis tool
             */
            visualStudioSolution.SolutionBuild.Clean(true);
            visualStudioSolution.SolutionBuild.Build(true);

            ErrorItems errors = dte.ToolWindows.ErrorList.ErrorItems;

            Console.WriteLine("Errors count: " + errors.Count);
            int tcStaticAnalysisWarnings = 0;
            int tcStaticAnalysisErrors   = 0;

            for (int i = 1; i <= errors.Count; i++)
            {
                ErrorItem item = errors.Item(i);
                if (item.Description.StartsWith("SA") && (item.ErrorLevel != vsBuildErrorLevel.vsBuildErrorLevelLow))
                {
                    Console.WriteLine("Description: " + item.Description);
                    Console.WriteLine("ErrorLevel: " + item.ErrorLevel);
                    Console.WriteLine("Filename: " + item.FileName);
                    if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium)
                    {
                        tcStaticAnalysisWarnings++;
                    }
                    else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh)
                    {
                        tcStaticAnalysisErrors++;
                    }
                }
            }

            dte.Quit();

            MessageFilter.Revoke();

            /* Return the result to the user */
            if (tcStaticAnalysisErrors > 0)
            {
                return(Constants.RETURN_ERROR);
            }
            else if (tcStaticAnalysisWarnings > 0)
            {
                return(Constants.RETURN_UNSTABLE);
            }
            else
            {
                return(Constants.RETURN_SUCCESSFULL);
            }
        }
        private void LoadDevelopmentToolsEnvironment(string visualStudioVersion, bool isTwinCatVersionPinned)
        {
            /* Make sure the DTE loads with the same version of Visual Studio as the
             * TwinCAT project was created in
             */

            // Load the DTE
            string VisualStudioProgId      = VisualStudioDteAvailable(visualStudioVersion);
            bool   isVersionAvailable      = false;
            bool   isForceVersionAvailable = false;

            dte.UserControl = false; // have devenv.exe automatically close when launched using automation
            dte.SuppressUI  = true;
            // Make sure all types of errors in the error list are collected
            dte.ToolWindows.ErrorList.ShowErrors   = true;
            dte.ToolWindows.ErrorList.ShowMessages = true;
            dte.ToolWindows.ErrorList.ShowWarnings = true;
            // First set the SilentMode and then try to open the Remote Manager
            var tcAutomationSettings = dte.GetObject("TcAutomationSettings");

            tcAutomationSettings.SilentMode = true; // Only available from TC3.1.4020.0 and above

            // Load the correct version of TwinCAT using the remote manager in the automation interface
            ITcRemoteManager remoteManager = dte.GetObject("TcRemoteManager");

            var     allTwinCatVersions   = new List <Version>();
            Version latestTwinCatVersion = null;

            // Check if version is installed
            foreach (var possibleVersion in remoteManager.Versions)
            {
                // Add installed TwinCAT version to versions list
                allTwinCatVersions.Add(new Version(possibleVersion));

                if (possibleVersion == this.tcVersion)
                {
                    isVersionAvailable = true;
                }
                // Check if forced version is installed
                if (possibleVersion == this.forceToThisTwinCatVersion && this.forceToThisTwinCatVersion != null)
                {
                    isForceVersionAvailable = true;
                    log.Info("The forced TwinCAT version is available");
                }
            }

            // Find latest installed TwinCAT version
            latestTwinCatVersion = allTwinCatVersions.Max();

            // If the version is pinned, check if the pinned version is available
            if (isTwinCatVersionPinned && (String.IsNullOrEmpty(this.forceToThisTwinCatVersion)))
            {
                if (isVersionAvailable)
                {
                    log.Info("The pinned TwinCAT version is available");
                }
                else
                {
                    log.Error("The pinned TwinCAT version is not available");
                    throw new Exception("The pinned TwinCAT version is not available");
                }
            }


            /* The basic procedure/priority for selection of which TwinCAT version should be used is as this:
             * - If TwinCAT project version is forced (by -w argument to TcUnit-Runner), go with this version, otherwise...
             * - If TwinCAT project is pinned, go with this version, otherwise...
             * - Go with latest installed version of TwinCAT
             */
            if (isTwinCatVersionPinned && isVersionAvailable && (String.IsNullOrEmpty(this.forceToThisTwinCatVersion)))
            {
                remoteManager.Version = this.tcVersion;
            }
            else if (isForceVersionAvailable)
            {
                log.Info("TwinCAT version is forced to " + this.forceToThisTwinCatVersion);
                remoteManager.Version = this.forceToThisTwinCatVersion;
            }
            else if (!isForceVersionAvailable && (!String.IsNullOrEmpty(this.forceToThisTwinCatVersion)))
            {
                log.Error("The forced TwinCAT version " + this.forceToThisTwinCatVersion + " is not available");
                throw new Exception("The forced TwinCAT version is not available");
            }
            else if (latestTwinCatVersion != null)
            {
                remoteManager.Version = latestTwinCatVersion.ToString();
            }
            else
            {
                log.Error("Error: It´s not possible to run TwinCAT in this configuration (TwinCAT-ForcedVersion / pinned TwinCAT Version / installed TwinCAT Version ");
                throw new Exception("Wrong configuration for this TwinCAT version");
            }

            // Log the Version which will be loaded
            log.Info("Using the TwinCAT remote manager to load TwinCAT version '" + remoteManager.Version + "'...");
        }