/// <summary> /// Closes the DTE and makes sure the VS process is completely shutdown /// </summary> public void Close() { if (loaded) { log.Info("Closing the Visual Studio Development Tools Environment (DTE)..."); Thread.Sleep(20000); // Avoid 'Application is busy'-problem (RPC_E_CALL_REJECTED 0x80010001 or RPC_E_SERVERCALL_RETRYLATER 0x8001010A) dte.Quit(); } loaded = false; }
/// <summary> /// Closes the DTE and makes sure the VS process is completely shutdown /// </summary> public void Close() { if (loaded) { log.Info("Closing the Visual Studio Development Tools Environment (DTE), please wait..."); Thread.Sleep(20000); // Makes sure that there are no visual studio processes left in the system if the user interrupts this program (for example by CTRL+C) dte.Quit(); } loaded = false; }
/// <summary> /// Loads and edits the specified Visual Studio solution with values from Config. This function /// will load visual studio and interact with it through Visual Studio's automation interface. /// If it fails then it's likely that the user will be left with a copy of DevEnv.exe running /// in the background. /// </summary> /// <param name="studentSolutionPath">Path to student version of the sln</param> public void ProcessSolution(string studentSolutionPath) { OutputLine("Creating instance of VisualStudio..."); System.Type dteType = System.Type.GetTypeFromProgID("VisualStudio.DTE.11.0", true); EnvDTE80.DTE2 devEnvInstance = (EnvDTE80.DTE2)System.Activator.CreateInstance(dteType, true); MessageFilter.Register(); //devEnvInstance.MainWindow.Activate(); ProcessSolution(studentSolutionPath, devEnvInstance.Solution as Solution2); devEnvInstance.Quit(); MessageFilter.Revoke(); }
/// <summary> /// Removes VCB toolbar and menu from Visual Studio. /// </summary> /// <param name="progId"> /// ID of the Visual Studio. /// </param> public static void Remove(string progId) { DTE dte = null; try { Type t = Type.GetTypeFromProgID(progId); if (t != null) { dte = (DTE)Activator.CreateInstance(t); Debug.Assert(dte != null); DeleteCommands(dte); DeleteBars(dte); } } finally { if (dte != null) { dte.Quit(); } } }
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); } }
public static void OpenSolution(object sender, DoWorkEventArgs e) { bwAsync = sender as BackgroundWorker; EnvDTE80.DTE2 dte = null; Dictionary <string, IUMLElement> listElements = new Dictionary <string, IUMLElement>(); try { dte = (EnvDTE80.DTE2)Microsoft.VisualBasic.Interaction.CreateObject("VisualStudio.DTE.8.0", ""); Solution2 soln = (Solution2)dte.Solution; soln.Open(File); SolutionBuild2 build = (SolutionBuild2)soln.SolutionBuild; addMessageBackgroundWorker(0, "Building Solution..."); build.SolutionConfigurations.Item("Debug").Activate(); build.Clean(true); build.Build(true); UMLModel model = Helper.GetCurrentElement <UMLModel>(); if (build.LastBuildInfo == 0 && model != null) { IUMLElement solutionUML = new UMLPackage(); solutionUML.Name = Path.GetFileName(soln.FileName); solutionUML.Owner = model; listElements.Add(solutionUML.Name, solutionUML); for (int i = 1; i <= soln.Projects.Count; i++) { Project project = soln.Projects.Item(i); if (project.Properties != null) { string fullPath = (string)project.Properties.Item("FullPath").Value; string outputfileName = (string)project.Properties.Item("OutputFileName").Value; Assembly assembly = Assembly.LoadFile(fullPath + @"Bin\Debug\" + outputfileName); IUMLElement projectUML = new UMLPackage(); projectUML.Name = project.Name; listElements.Add(project.Name, projectUML); projectUML.Owner = solutionUML; addMessageBackgroundWorker(0, "Processing Types: \n" + project.Name); foreach (Type type in assembly.GetTypes()) { if (type.MemberType == MemberTypes.TypeInfo) { IUMLElement element = null; if (type.IsEnum && IncludeEnumeration) { element = new UMLEnumeration(); element.Name = type.Name; ((UMLEnumeration)element).Literals = GetLiterals(type); } else { if (type.IsClass && IncludeClass) { element = new UMLClass(); element.Name = type.Name; ((UMLClass)element).Attributes = GetProperties(type); ((UMLClass)element).Attributes.AddRange(GetStaticAndConstants(type)); ((UMLClass)element).Methods = GetMethods(type); if (type.IsGenericType) { element.Name = element.Name.Substring(0, element.Name.IndexOf("`")); element.Name += "<"; foreach (Type t in type.GetGenericArguments()) { element.Name += t.Name + ","; } element.Name = element.Name.TrimEnd(','); element.Name += ">"; } } else if (type.IsInterface && IncludeInterface) { element = new UMLInterface(); element.Name = type.Name; ((UMLInterface)element).Attributes = GetProperties(type); } } if (element != null) { IUMLElement owner = null; if (type.Namespace == null) { owner = projectUML; } else if (listElements.ContainsKey(type.Namespace)) { owner = listElements[type.Namespace]; } else { owner = new UMLPackage(); //if(type.Namespace.Contains(projectUML.Name)) //{ // owner.Name = type.Namespace.Replace(projectUML.Name, ""); //} owner.Stereotype = "ClassPackage"; owner.Name = type.Namespace; owner.Owner = projectUML; listElements.Add(type.Namespace, owner); } element.Owner = owner; if ((type.Attributes & TypeAttributes.Public) == TypeAttributes.Public) { element.Visibility = Visibility.Public; } else { element.Visibility = Visibility.Private; } XmlNode node = DocsByReflection.XMLFromType(type); if (node != null) { element.Documentation = node.InnerXml.Trim(); } if (!listElements.ContainsKey(type.Namespace + "." + type.Name)) { listElements.Add(type.Namespace + "." + type.Name, element); } } } } } } } else { // Error Build } soln.Close(true); } catch (SystemException ex) { //MessageBox.Show("ERROR: " + ex); } finally { if (dte != null) { dte.Quit(); } } Helper.BeginUpdate(); addMessageBackgroundWorker(0, "Init import..."); int pos = 0; foreach (IUMLElement element in listElements.Values) { pos++; addMessageBackgroundWorker((pos * 100) / listElements.Count, "Creating: \n" + element.Name); element.GetType().InvokeMember("Save", BindingFlags.Default | BindingFlags.InvokeMethod, null, element, new object[] { }); } addMessageBackgroundWorker(100, "End import"); Helper.EndUpdate(); }
/// <summary> /// create solution and output proj in other thread /// solution name = project name /// </summary> private bool RunLongProcess(List <FileInfo> files, String projName, String folderOutputPath , string path_to_GUI_Testing_Automation_ref , string path_to_vstemplate_output_proj , string tempProjectFolder , List <string> runningTestFilesRelativePath , List <string> otherFilesRelativePath , string AUTPath) { EnvDTE80.DTE2 dte2 = null; string folderSolution = folderOutputPath; string folderOutputProj = folderOutputPath + "\\" + projName; string solutionName = projName + ".sln"; string outputProjName = projName; string pathTo_csproj = folderOutputProj + "\\" + outputProjName + ".csproj"; //string pathToSolution = folderSolution + "\\" + solutionName; //get solution2 as part of visual studio string versionDTE = "VisualStudio.DTE.15.0"; System.Type dteType = System.Type.GetTypeFromProgID(versionDTE, true); dte2 = (EnvDTE80.DTE2)System.Activator.CreateInstance(dteType, true); MessageFilter.Register(); Solution2 sol = (Solution2)dte2.Solution; //delete the old folder_solution if it exists. if (Directory.Exists(folderSolution)) { Directory.Delete(folderSolution, true); } //create a new folder_solution Directory.CreateDirectory(folderSolution); //create a solution that locates in the above solution sol.Create(folderSolution, solutionName); //create a new folder_output_project Directory.CreateDirectory(folderOutputProj); Project outputProj = sol.AddFromTemplate(path_to_vstemplate_output_proj , folderOutputProj, outputProjName, false); //save the solution sol.SaveAs(solutionName); // for kill process dte2.Quit(); MessageFilter.Revoke(); var t1 = DateTime.Now; while (dte2 != null && (DateTime.Now - t1).TotalSeconds < 5) { //dte2. try { dte2.Quit(); } catch (Exception) { } System.Threading.Thread.Sleep(1000); } ModifyProject(files, folderOutputProj, runningTestFilesRelativePath, otherFilesRelativePath, tempProjectFolder, pathTo_csproj, path_to_GUI_Testing_Automation_ref, projName, AUTPath); return(true); }