// adds the mappings between errors in the generated parser-file and their corresponding position in the grammar file (semantic actions).
        private void OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
        {
            DTE2       dte      = (DTE2)GetService(typeof(DTE));
            ErrorItems errors   = dte.ToolWindows.ErrorList.ErrorItems;
            Hashtable  mapCache = new Hashtable();

            bool grammarErrorFound = false;

            for (uint i = 1; i <= errors.Count; i++)
            {
                ErrorItem error = errors.Item(i);

                string fn  = Path.GetFileName(error.FileName);
                string dir = Path.GetDirectoryName(error.FileName);
                if (fn.ToLower() == "parser.cs")
                {
                    string  atgmap = Path.Combine(dir, "parser.atgmap");
                    Mapping map    = null;
                    if (mapCache.ContainsKey(atgmap))
                    {
                        map = (Mapping)mapCache[atgmap];
                    }
                    else
                    {
                        if (File.Exists(atgmap))
                        {
                            map = new Mapping();
                            map.Read(atgmap);
                            mapCache[atgmap] = map;
                        }
                    }

                    if (map != null)
                    {
                        int line, column;
                        if (map.Get(error.Line - 1, error.Column - 1, out line,
                                    out column))
                        {
                            ErrorTask task = new ErrorTask();
                            task.ErrorCategory = TaskErrorCategory.Error;
                            task.Priority      = TaskPriority.Normal;
                            task.Text          = error.Description;
                            task.Column        = column;
                            task.Line          = line;
                            task.Document      = map.Grammar;
                            task.Navigate     += NavigateDocument;
                            errorListProvider.Tasks.Add(task);
                            grammarErrorFound = true;
                        }
                    }
                }
            }

            if (grammarErrorFound)
            {
                errorListProvider.Show();
            }
        }
        private bool AreErrorItemsContainingTestMessage(string testMessage)
        {
            bool result = false;

            for (int i = 1; i <= _errorItems.Count; i++)
            {
                ErrorItem item = _errorItems.Item(i);
                if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh)
                {
                    if (item.Description.ToUpper().Contains(testMessage.ToUpper()))
                    {
                        result = true;
                        break;
                    }
                }
            }
            return(result);
        }
        public ErrorListNodeFactory(ErrorItems items, DTE2 dte)
        {
            _dte   = dte;
            _items = new List <ErrorItem>(items.Count);

            for (int i = 0; i < items.Count; ++i)
            {
                _items.Add(items.Item(i + 1));
            }
        }
        public ErrorListNodeFactory(ErrorItems items, DTE2 dte)
        {
            _dte = dte;
            _items = new List<ErrorItem>(items.Count);

            for (int i = 0; i < items.Count; ++i)
            {
                _items.Add(items.Item(i + 1));
            }
        }
        private bool CompileProject(IWorker worker, out ErrorItems errors)
        {
            bool buildSucceeded = false;

            if (worker.CancellationPending)
            {
                throw new Exception("Execution cancelled!");
            }

            worker.ProgressStatus = "Compiling project ...";

            dte.Solution.SolutionBuild.Build(true);
            buildSucceeded = waitForBuildAndCheckErrors(worker, out errors);

            if (!buildSucceeded)
            {
                int overallMessages = errors.Count;

                int errorCount   = 0;
                int warningCount = 0;
                int messageCount = 0;

                for (int i = 1; i <= overallMessages; i++) // List is starting from 1!!!
                {
                    ErrorItem item = errors.Item(i);

                    if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh)
                    {
                        errorCount++;
                        worker.ProgressStatus = "Compiler error: " + item.Description;
                    }
                    else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium)
                    {
                        warningCount++;
                        worker.ProgressStatus = "Compiler warning: " + item.Description;
                    }
                    else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelLow)
                    {
                        messageCount++;
                        worker.ProgressStatus = "Compiler message: " + item.Description;
                    }
                }
            }
            else
            {
                worker.ProgressStatus = "Build Succeeded!";
            }

            if (worker.CancellationPending)
            {
                throw new Exception("Execution cancelled!");
            }

            return(buildSucceeded);
        }
Beispiel #6
0
        public IEnumerable <Error> AddNew(ErrorItems errorItems)
        {
            int N1 = _errors.Count + 1;
            int N2 = errorItems.Count;

            for (int i = N1; i <= N2; i++)
            {
                var item = errorItems.Item(i);
                _errors.Add(new Error(item));
            }
            return(_errors.GetRange(N1 - 1, N2 + 1 - N1));
        }
Beispiel #7
0
        private List <ErrorItem> GetErrors()
        {
            ErrorItems       errors = envDte2.ToolWindows.ErrorList.ErrorItems;
            List <ErrorItem> listOfSelecteedItems = new List <ErrorItem>();

            for (int i = 1; i <= errors.Count; i++)
            {
                ErrorItem item = errors.Item(i);
                listOfSelecteedItems.Add(item);
            }
            return(listOfSelecteedItems);
        }
Beispiel #8
0
        public void printErrors()
        {
            Dictionary <vsBuildErrorLevel, String> errorLevel = new Dictionary <vsBuildErrorLevel, String>()
            {
                { vsBuildErrorLevel.vsBuildErrorLevelHigh, "Error" },
                { vsBuildErrorLevel.vsBuildErrorLevelMedium, "Warning" },
                { vsBuildErrorLevel.vsBuildErrorLevelLow, "Info" }
            };
            ErrorItems errorItems = dte.ToolWindows.ErrorList.ErrorItems;

            var errors = from i in Enumerable.Range(1, errorItems.Count) select errorItems.Item(i);

            var newErrors = errors.Except(lastErrors, new ErrorComparer());

            newErrors.ToList().ForEach(error => Console.WriteLine("Build " + errorLevel[error.ErrorLevel] + ": " + error.Description));
            lastErrors = errors.ToList();
        }
Beispiel #9
0
        void mBuildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
        {
            if (!TaskbarManager.IsPlatformSupported)
            {
                return;
            }

            mWindowsTaskBar.SetProgressState(TaskbarProgressBarState.NoProgress);

            if (mBuildError)
            {
                mWindowsTaskBar.SetOverlayIcon(IconTheme.IconBuildFail(mSettings.Theme), "Build Failed");
            }
            else
            {
                bool buildWarnings = false;

                if (mSettings.ShowWarnings)
                {
                    try
                    {
                        ErrorItems errorList = (mDTE as EnvDTE80.DTE2).ToolWindows.ErrorList.ErrorItems;
                        for (int i = 1; i <= errorList.Count; i++)
                        {
                            ErrorItem e = errorList.Item(i);

                            if (e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium)
                            {
                                buildWarnings = true;
                                break;
                            }
                        }
                    }
                    catch { }
                }

                if (buildWarnings)
                {
                    mWindowsTaskBar.SetOverlayIcon(IconTheme.IconBuildWarning(mSettings.Theme), "Build Successful with Warnings");
                }
                else
                {
                    mWindowsTaskBar.SetOverlayIcon(IconTheme.IconBuildOK(mSettings.Theme), "Build Successful");
                }
            }
        }
Beispiel #10
0
        void UpdateErrorList()
        {
            _errors.Clear();

            try
            {
                for (int i = 1; i <= _errorList.Count; i++)
                {
                    ErrorItem e = _errorList.Item(i);

                    if (e.FileName.Equals(_textDocument.FilePath))
                    {
                        ITextSnapshotLine line = _textBuffer.CurrentSnapshot.GetLineFromLineNumber(e.Line - 1);

                        if (_errors.ContainsKey(e.Line))
                        {
                            ErrorTagInfo errorItem = _errors[e.Line];
                            errorItem.Description += Environment.NewLine + Environment.NewLine + e.Description;
                            if (errorItem.ErrorLevel < e.ErrorLevel)
                            {
                                errorItem.ErrorLevel = e.ErrorLevel;
                            }
                        }
                        else
                        {
                            ErrorTagInfo errorItem = new ErrorTagInfo();
                            errorItem.Description = e.Description;
                            errorItem.ErrorLevel  = e.ErrorLevel;
                            errorItem.SpanData    = new SnapshotSpan(_textBuffer.CurrentSnapshot, line.Start, line.Length);

                            _errors[e.Line] = errorItem;
                        }
                    }
                }
            }
            catch { }

            if (TagsChanged != null)
            {
                TagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(_textBuffer.CurrentSnapshot, 0, _textBuffer.CurrentSnapshot.Length)));
            }
        }
Beispiel #11
0
        /// <summary>
        /// Returns whether results are finished collecting
        /// </summary>
        /// <returns>Whether TcUnit results are available</returns>
        public bool AreResultsAvailable(ErrorItems errorItems)
        {
            string line;

            // First check if we already have results
            if (AreTestResultsAvailable())
            {
                return(true);
            }
            else
            {
                for (int i = 1; i <= errorItems.Count; i++)
                {
                    ErrorItem error = errorItems.Item(i);
                    line = error.Description;
                    if (line.Contains(tcUnitResult_TestSuites))
                    {
                        string noTestSuites = line.Substring(line.LastIndexOf(tcUnitResult_TestSuites) + tcUnitResult_TestSuites.Length + 1);
                        Int32.TryParse(noTestSuites, out numberOfTestSuites);
                    }
                    if (line.Contains(tcUnitResult_Tests))
                    {
                        string noTests = line.Substring(line.LastIndexOf(tcUnitResult_Tests) + tcUnitResult_Tests.Length + 1);
                        Int32.TryParse(noTests, out numberOfTests);
                    }
                    if (line.Contains(tcUnitResult_SuccessfulTests))
                    {
                        string noSuccessfulTests = line.Substring(line.LastIndexOf(tcUnitResult_SuccessfulTests) + tcUnitResult_SuccessfulTests.Length + 1);
                        Int32.TryParse(noSuccessfulTests, out numberOfSuccessfulTests);
                    }
                    if (line.Contains(tcUnitResult_FailedTests))
                    {
                        string noFailedTests = line.Substring(line.LastIndexOf(tcUnitResult_FailedTests) + tcUnitResult_FailedTests.Length + 1);
                        Int32.TryParse(noFailedTests, out numberOfFailedTests);
                    }
                }
                return(AreTestResultsAvailable());
            }
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            bool showHelp = false;
            bool enableDebugLoggingLevel = false;

            Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelKeyPressHandler);
            log4net.GlobalContext.Properties["LogLocation"] = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));

            OptionSet options = new OptionSet()
                                .Add("v=|VisualStudioSolutionFilePath=", "The full path to the TwinCAT project (sln-file)", v => VisualStudioSolutionFilePath = v)
                                .Add("t=|TcUnitTaskName=", "[OPTIONAL] The name of the task running TcUnit defined under \"Tasks\"", t => TcUnitTaskName      = t)
                                .Add("a=|AmsNetId=", "[OPTIONAL] The AMS NetId of the device of where the project and TcUnit should run", a => AmsNetId       = a)
                                .Add("w=|TcVersion=", "[OPTIONAL] The TwinCAT version to be used to load the TwinCAT project", w => ForceToThisTwinCATVersion = w)
                                .Add("u=|Timeout=", "[OPTIONAL] Timeout the process with an error after X minutes", u => Timeout = u)
                                .Add("d|debug", "[OPTIONAL] Increase debug message verbosity", d => enableDebugLoggingLevel      = d != null)
                                .Add("?|h|help", h => showHelp = h != null);

            try
            {
                options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `TcUnit-Runner --help' for more information.");
                Environment.Exit(Constants.RETURN_ARGUMENT_ERROR);
            }


            if (showHelp)
            {
                DisplayHelp(options);
                Environment.Exit(Constants.RETURN_SUCCESSFULL);
            }

            /* Set logging level.
             * This is handled by changing the log4net.config file on the fly.
             * The following levels are defined in order of increasing priority:
             * - ALL
             * - DEBUG
             * - INFO
             * - WARN
             * - ERROR
             * - FATAL
             * - OFF
             */
            XmlDocument doc = new XmlDocument();

            doc.Load(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
            XmlNode root          = doc.DocumentElement;
            XmlNode subNode1      = root.SelectSingleNode("root");
            XmlNode nodeForModify = subNode1.SelectSingleNode("level");

            if (enableDebugLoggingLevel)
            {
                nodeForModify.Attributes[0].Value = "DEBUG";
            }
            else
            {
                nodeForModify.Attributes[0].Value = "INFO";
            }
            doc.Save(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
            System.Threading.Thread.Sleep(500); // A tiny sleep just to make sure that log4net manages to detect the change in the file

            /* Make sure the user has supplied the path for the Visual Studio solution file.
             * Also verify that this file exists.
             */
            if (VisualStudioSolutionFilePath == null)
            {
                log.Error("Visual studio solution path not provided!");
                Environment.Exit(Constants.RETURN_VISUAL_STUDIO_SOLUTION_PATH_NOT_PROVIDED);
            }

            if (!File.Exists(VisualStudioSolutionFilePath))
            {
                log.Error("Visual studio solution " + VisualStudioSolutionFilePath + " does not exist!");
                Environment.Exit(Constants.RETURN_VISUAL_STUDIO_SOLUTION_PATH_NOT_FOUND);
            }

            LogBasicInfo();

            /* Start a timeout for the process(es) if the user asked for it
             */
            if (Timeout != null)
            {
                log.Info("Timeout enabled - process(es) timesout after " + Timeout + " minute(s)");
                System.Timers.Timer timeout = new System.Timers.Timer(Int32.Parse(Timeout) * 1000 * 60);
                timeout.Elapsed  += KillProcess;
                timeout.AutoReset = false;
                timeout.Start();
            }

            MessageFilter.Register();

            TwinCATProjectFilePath = TcFileUtilities.FindTwinCATProjectFile(VisualStudioSolutionFilePath);
            if (String.IsNullOrEmpty(TwinCATProjectFilePath))
            {
                log.Error("Did not find TwinCAT project file in solution. Is this a TwinCAT project?");
                Environment.Exit(Constants.RETURN_TWINCAT_PROJECT_FILE_NOT_FOUND);
            }

            if (!File.Exists(TwinCATProjectFilePath))
            {
                log.Error("TwinCAT project file " + TwinCATProjectFilePath + " does not exist!");
                Environment.Exit(Constants.RETURN_TWINCAT_PROJECT_FILE_NOT_FOUND);
            }

            string tcVersion = TcFileUtilities.GetTcVersion(TwinCATProjectFilePath);

            if (String.IsNullOrEmpty(tcVersion))
            {
                log.Error("Did not find TwinCAT version in TwinCAT project file path");
                Environment.Exit(Constants.RETURN_TWINCAT_VERSION_NOT_FOUND);
            }

            try
            {
                vsInstance = new VisualStudioInstance(@VisualStudioSolutionFilePath, tcVersion, ForceToThisTwinCATVersion);
                bool isTcVersionPinned = XmlUtilities.IsTwinCATProjectPinned(TwinCATProjectFilePath);
                log.Info("Version is pinned: " + isTcVersionPinned);
                vsInstance.Load(isTcVersionPinned);
            }
            catch
            {
                log.Error("Error loading VS DTE. Is the correct version of Visual Studio and TwinCAT installed? Is the TcUnit-Runner running with administrator privileges?");
                CleanUpAndExitApplication(Constants.RETURN_ERROR_LOADING_VISUAL_STUDIO_DTE);
            }

            try
            {
                vsInstance.LoadSolution();
            }
            catch
            {
                log.Error("Error loading the solution. Try to open it manually and make sure it's possible to open and that all dependencies are working");
                CleanUpAndExitApplication(Constants.RETURN_ERROR_LOADING_VISUAL_STUDIO_SOLUTION);
            }

            if (vsInstance.GetVisualStudioVersion() == null)
            {
                log.Error("Did not find Visual Studio version in Visual Studio solution file");
                CleanUpAndExitApplication(Constants.RETURN_ERROR_FINDING_VISUAL_STUDIO_SOLUTION_VERSION);
            }


            AutomationInterface automationInterface = new AutomationInterface(vsInstance.GetProject());

            if (automationInterface.PlcTreeItem.ChildCount <= 0)
            {
                log.Error("No PLC-project exists in TwinCAT project");
                CleanUpAndExitApplication(Constants.RETURN_NO_PLC_PROJECT_IN_TWINCAT_PROJECT);
            }


            ITcSmTreeItem realTimeTasksTreeItem = automationInterface.RealTimeTasksTreeItem;

            /* Task name provided */
            if (!String.IsNullOrEmpty(TcUnitTaskName))
            {
                log.Info("Setting task '" + TcUnitTaskName + "' enable and autostart, and all other tasks (if existing) to disable and non-autostart");
                bool foundTcUnitTaskName = false;

                /* Find all tasks, and check whether the user provided TcUnit task is amongst them.
                 * Also update the task object (Update <Disabled> and <Autostart>-tag)
                 */
                foreach (ITcSmTreeItem child in realTimeTasksTreeItem)
                {
                    ITcSmTreeItem testTreeItem = realTimeTasksTreeItem.LookupChild(child.Name);
                    string        xmlString    = testTreeItem.ProduceXml();
                    string        newXmlString = "";
                    try
                    {
                        if (TcUnitTaskName.Equals(XmlUtilities.GetItemNameFromRealTimeTaskXML(xmlString)))
                        {
                            foundTcUnitTaskName = true;
                            newXmlString        = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, false, true);
                        }
                        else
                        {
                            newXmlString = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, true, false);
                        }
                        testTreeItem.ConsumeXml(newXmlString);
                        System.Threading.Thread.Sleep(3000);
                    }
                    catch
                    {
                        log.Error("Could not parse real time task XML data");
                        CleanUpAndExitApplication(Constants.RETURN_NOT_POSSIBLE_TO_PARSE_REAL_TIME_TASK_XML_DATA);
                    }
                }

                if (!foundTcUnitTaskName)
                {
                    log.Error("Could not find task '" + TcUnitTaskName + "' in TwinCAT project");
                    CleanUpAndExitApplication(Constants.RETURN_FAILED_FINDING_DEFINED_UNIT_TEST_TASK_IN_TWINCAT_PROJECT);
                }
            }

            /* No task name provided */
            else
            {
                log.Info("No task name provided. Assuming only one task exists");
                /* Check that only one task exists */
                if (realTimeTasksTreeItem.ChildCount.Equals(1))
                {
                    // Get task name
                    ITcSmTreeItem child        = realTimeTasksTreeItem.get_Child(1);
                    ITcSmTreeItem testTreeItem = realTimeTasksTreeItem.LookupChild(child.Name);
                    string        xmlString    = testTreeItem.ProduceXml();
                    TcUnitTaskName = XmlUtilities.GetItemNameFromRealTimeTaskXML(xmlString);
                    log.Info("Found task with name '" + TcUnitTaskName + "'");
                    string newXmlString = "";
                    newXmlString = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, false, true);
                    testTreeItem.ConsumeXml(newXmlString);
                    System.Threading.Thread.Sleep(3000);
                }
                /* Less ore more than one task, which is an error */
                else
                {
                    log.Error("The number of tasks is not equal to 1 (one). Found " + realTimeTasksTreeItem.ChildCount.ToString() + " number of tasks. Please provide which task is the TcUnit task");
                    CleanUpAndExitApplication(Constants.RETURN_TASK_COUNT_NOT_EQUAL_TO_ONE);
                }
            }


            /* Build the solution and collect any eventual errors. Make sure to
             * filter out everything that is an error
             */
            vsInstance.CleanSolution();
            vsInstance.BuildSolution();

            ErrorItems errorsBuild = vsInstance.GetErrorItems();

            int tcBuildWarnings = 0;
            int tcBuildError    = 0;

            for (int i = 1; i <= errorsBuild.Count; i++)
            {
                ErrorItem item = errorsBuild.Item(i);
                if ((item.ErrorLevel != vsBuildErrorLevel.vsBuildErrorLevelLow))
                {
                    if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium)
                    {
                        tcBuildWarnings++;
                    }
                    else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh)
                    {
                        tcBuildError++;
                        log.Error("Description: " + item.Description);
                        log.Error("ErrorLevel: " + item.ErrorLevel);
                        log.Error("Filename: " + item.FileName);
                    }
                }
            }

            /* If we don't have any errors, activate the configuration and
             * start/restart TwinCAT */
            if (tcBuildError.Equals(0))
            {
                /* Check whether the user has provided an AMS NetId. If so, use it. Otherwise use
                 * the local AMS NetId */
                if (String.IsNullOrEmpty(AmsNetId))
                {
                    AmsNetId = Constants.LOCAL_AMS_NET_ID;
                }

                log.Info("Setting target NetId to '" + AmsNetId + "'");
                automationInterface.ITcSysManager.SetTargetNetId(AmsNetId);
                log.Info("Enabling boot project and setting BootProjectAutostart on " + automationInterface.ITcSysManager.GetTargetNetId());

                for (int i = 1; i <= automationInterface.PlcTreeItem.ChildCount; i++)
                {
                    ITcSmTreeItem plcProject = automationInterface.PlcTreeItem.Child[i];
                    ITcPlcProject iecProject = (ITcPlcProject)plcProject;
                    iecProject.BootProjectAutostart = true;

                    /* add the port that is used for this PLC to the AmsPorts list that
                     * is later used to monitory the AdsState
                     */
                    string xmlString = plcProject.ProduceXml();
                    AmsPorts.Add(XmlUtilities.AmsPort(xmlString));
                }
                System.Threading.Thread.Sleep(1000);
                automationInterface.ActivateConfiguration();

                // Wait
                System.Threading.Thread.Sleep(10000);

                /* Clean the solution. This is the only way to clean the error list which needs to be
                 * clean prior to starting the TwinCAT runtime */
                vsInstance.CleanSolution();

                // Wait
                System.Threading.Thread.Sleep(10000);

                automationInterface.StartRestartTwinCAT();
            }
            else
            {
                log.Error("Build errors in project");
                CleanUpAndExitApplication(Constants.RETURN_BUILD_ERROR);
            }

            /* Establish a connection to the ADS router
             */
            TcAdsClient tcAdsClient = new TcAdsClient();

            /* Run TcUnit until the results have been returned */
            TcUnitResultCollector tcUnitResultCollector = new TcUnitResultCollector();
            ErrorList             errorList             = new ErrorList();

            log.Info("Waiting for results from TcUnit...");

            ErrorItems errorItems;

            while (true)
            {
                System.Threading.Thread.Sleep(10000);

                /* Monitor the AdsState for each PLC that is used in the
                 * solution. If we can't connect to the Ads Router, we just
                 * carry on.
                 */
                try
                {
                    foreach (int amsPort in AmsPorts)
                    {
                        tcAdsClient.Connect(AmsNetId, amsPort);
                        AdsState adsState = tcAdsClient.ReadState().AdsState;
                        if (adsState != AdsState.Run)
                        {
                            log.Error("Invalid AdsState " + adsState + "<>" + AdsState.Run + ". This could indicate a PLC Exception, terminating ...");
                            Environment.Exit(Constants.RETURN_INVALID_ADSSTATE);
                        }
                    }
                }
                catch (Exception ex)
                { }
                finally
                {
                    tcAdsClient.Disconnect();
                }

                errorItems = vsInstance.GetErrorItems();

                var newErrors = errorList.AddNew(errorItems);
                if (log.IsDebugEnabled)
                {
                    foreach (var error in newErrors)
                    {
                        log.Debug(error.ErrorLevel + ": " + error.Description);
                    }
                }

                log.Info("... got " + errorItems.Count + " report lines so far.");
                if (tcUnitResultCollector.AreResultsAvailable(errorItems))
                {
                    log.Info("All results from TcUnit obtained");

                    /* The last test suite result can be returned after that we have received the test results, wait a few seconds
                     * and fetch again
                     */
                    System.Threading.Thread.Sleep(10000);
                    break;
                }
            }

            List <ErrorList.Error> errors       = new List <ErrorList.Error>(errorList.Where(e => (e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh || e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelLow)));
            List <ErrorList.Error> errorsSorted = errors.OrderBy(o => o.Description).ToList();

            /* Parse all events (from the error list) from Visual Studio and store the results */
            TcUnitTestResult testResult = tcUnitResultCollector.ParseResults(errorsSorted, TcUnitTaskName);

            /* Write xUnit XML report */
            if (testResult != null)
            {
                // No need to check if file (VisualStudioSolutionFilePath) exists, as this has already been done
                string VisualStudioSolutionDirectoryPath = Path.GetDirectoryName(VisualStudioSolutionFilePath);
                string XUnitReportFilePath = VisualStudioSolutionDirectoryPath + "\\" + Constants.XUNIT_RESULT_FILE_NAME;
                log.Info("Writing xUnit XML file to " + XUnitReportFilePath);
                // Overwrites all existing content (if existing)
                XunitXmlCreator.WriteXml(testResult, XUnitReportFilePath);
            }

            CleanUpAndExitApplication(Constants.RETURN_SUCCESSFULL);
        }
        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);
            }
        }