private void OnDocumentSaved(EnvDTE.Document dteDocument) { var documentIds = this.workspace.CurrentSolution.GetDocumentIdsWithFilePath( dteDocument.FullName); if (documentIds != null && documentIds.Length == 1) { var documentId = documentIds[0]; var document = this.workspace.CurrentSolution.GetDocument(documentId); if (Path.GetExtension(document.FilePath) == ".cs") { SyntaxNode root = null; if (document.TryGetSyntaxRoot(out root)) { var newRoot = root.RemoveComments(); if (newRoot != root) { var newSolution = document.Project.Solution .WithDocumentSyntaxRoot(document.Id, newRoot); this.workspace.TryApplyChanges(newSolution); dteDocument.Save(); } } } } }
private void OnDocumentSaved(Document dteDocument) { var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(dteDocument.FullName); if (documentIds == null || documentIds.Length != 1) { return; } var documentId = documentIds[0]; var document = _workspace.CurrentSolution.GetDocument(documentId); if (Path.GetExtension(document.FilePath) != ".cs") { return; } SyntaxNode root; if (!document.TryGetSyntaxRoot(out root)) { return; } var newRoot = root.RemoveComments(); if (newRoot == root) { return; } var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot); _workspace.TryApplyChanges(newSolution); dteDocument.Save(); }
private void TrialAndErrorRemovalThreadFunc(EnvDTE.Document document, TrialAndErrorRemovalOptionsPage settings, Formatter.IncludeLineInfo[] includeLines, IVsThreadedWaitDialog2 progressDialog, ITextBuffer textBuffer) { int numRemovedIncludes = 0; bool canceled = false; try { //int currentProgressStep = 0; // For ever include line.. foreach (Formatter.IncludeLineInfo line in includeLines) { // If we are working from top to bottom, the line number may have changed! int currentLine = line.LineNumber; if (settings.RemovalOrder == TrialAndErrorRemovalOptionsPage.IncludeRemovalOrder.TopToBottom) { currentLine -= numRemovedIncludes; } ThreadHelper.JoinableTaskFactory.Run(async() => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); //// Update progress. //string waitMessage = $"Removing #includes from '{document.Name}'"; //string progressText = $"Trying to remove '{line.IncludeContent}' ..."; //progressDialog.UpdateProgress( // szUpdatedWaitMessage: waitMessage, // szProgressText: progressText, // szStatusBarText: "Running Trial & Error Removal - " + waitMessage + " - " + progressText, // iCurrentStep: currentProgressStep + 1, // iTotalSteps: includeLines.Length + 1, // fDisableCancel: false, // pfCanceled: out canceled); //if (!canceled) //{ // ++currentProgressStep; // // Remove include // using (var edit = textBuffer.CreateEdit()) // { // if (settings.KeepLineBreaks) // edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).Extent); // else // edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).ExtentIncludingLineBreak); // edit.Apply(); // } //} // Remove include using (var edit = textBuffer.CreateEdit()) { if (settings.KeepLineBreaks) { edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).Extent); } else { edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).ExtentIncludingLineBreak); } edit.Apply(); } outputWaitEvent.Set(); }); outputWaitEvent.WaitOne(); //if (canceled) // break; // Compile - In rare cases VS tells us that we are still building which should not be possible because we have received OnBuildFinished // As a workaround we just try again a few times. ThreadHelper.JoinableTaskFactory.Run(async() => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); const int maxNumCompileAttempts = 3; for (int numCompileFails = 0; numCompileFails < maxNumCompileAttempts; ++numCompileFails) { // TODO: This happens on the main thread. Making the whole thread thing a bit pointless!!! try { await VSUtils.VCUtils.CompileSingleFile(document); } catch (Exception e) { Output.Instance.WriteLine("Compile Failed:\n{0}", e); if (numCompileFails == maxNumCompileAttempts - 1) { document.Undo(); document.Save(); throw e; } else { // Try again. await System.Threading.Tasks.Task.Delay(100); continue; } } break; } }); // Wait till woken. bool noTimeout = outputWaitEvent.WaitOne(timeoutMS); // Undo removal if compilation failed. if (!noTimeout || !lastBuildSuccessful) { Output.Instance.WriteLine("Could not remove #include: '{0}'", line.IncludeContent); ThreadHelper.JoinableTaskFactory.Run(async() => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); document.Undo(); document.Save(); if (!noTimeout) { Output.Instance.WriteLine("Compilation of {0} timeouted!", document.Name); } }); if (!noTimeout) { break; } } else { //Output.Instance.WriteLine("Successfully removed #include: '{0}'", line.IncludeContent); ++numRemovedIncludes; } } } catch (Exception ex) { Output.Instance.WriteLine("Unexpected error: {0}", ex); } finally { _ = OnTrialAndErrorRemovalDone(progressDialog, document, numRemovedIncludes, canceled); } }
private static void addContentToProject(SolutionData solutionData, Project project, DTE2 dte2) { #region CPP Writing if (solutionData.projectType == ProjectType.CppEmpty) //CPP Example { Directory.CreateDirectory(solutionData.directoryPath + "\\Source Files"); Directory.CreateDirectory(solutionData.directoryPath + "\\Header Files"); foreach (ClassData classData in solutionData.classes) { #region Class if (classData.classType == ClassType.Class) { Document doc = dte2.ItemOperations.NewFile("General\\Text File", classData.className).Document; TextSelection txtsel = (TextSelection)doc.Selection; txtsel.Text = ""; txtsel.Insert("#include \"" + classData.className + ".h\"\n\n" + classData.className + "::" + classData.className + "()\n{\n}\n\n" + classData.className + "::~" + classData.className + "()\n{\n}"); doc.Save(solutionData.directoryPath + "\\Source Files\\" + classData.className + ".cpp"); project.ProjectItems.AddFromFile(solutionData.directoryPath + "\\Source Files\\" + classData.className + ".cpp"); Document doc2 = dte2.ItemOperations.NewFile("General\\Text File", classData.className).Document; TextSelection txtsel2 = (TextSelection)doc2.Selection; txtsel2.Text = ""; txtsel2.Insert("#pragma once"); if (classData.superClassName != "") { txtsel2.Insert("\n#include \"" + classData.superClassName + "\""); } foreach (string interfaceName in classData.interfaceNames) { txtsel2.Insert("\n#include \"" + interfaceName + "\""); } txtsel2.Insert("\n\nclass " + classData.className); if (classData.superClassName != "") { txtsel2.Insert(" : public " + classData.superClassName); foreach (string interfaceName in classData.interfaceNames) { txtsel2.Insert(", " + interfaceName); } } else if (classData.interfaceNames.Count != 0) { txtsel2.Insert(" : " + classData.interfaceNames[0]); for (int i = 1; i < classData.interfaceNames.Count; ++i) { txtsel2.Insert(", " + classData.interfaceNames[i]); } } txtsel2.Insert("\n{\npublic:\n\t" + classData.className + "();\n\t~" + classData.className + "();\n\nprivate:\n\n};"); doc2.Save(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h"); project.ProjectItems.AddFromFile(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h"); } #endregion #region Enum else if (classData.classType == ClassType.Enum) { EnvDTE.Document doc2 = dte2.ItemOperations.NewFile("General\\Text File", classData.className).Document; TextSelection txtsel2 = (TextSelection)doc2.Selection; txtsel2.Text = ""; txtsel2.Insert("#pragma once\n\nenum " + classData.className + "\n{\n\n};"); doc2.Save(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h"); project.ProjectItems.AddFromFile(solutionData.directoryPath + "\\Header Files\\" + classData.className + ".h"); } #endregion } } #endregion #region C# Writing else //C# Example { foreach (ProjectItem pItem in project.ProjectItems) { if (pItem.Name == "Form1.cs") { pItem.Remove(); } } foreach (ClassData classData in solutionData.classes) { if (classData.classType == ClassType.Enum || classData.classType == ClassType.Class || classData.classType == ClassType.Interface) { project.ProjectItems.AddFromTemplate(@"C:\Program Files (x86)\Microsoft Visual Studio " + dte2.Version + @"\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.vstemplate", classData.className + ".cs"); } else if (classData.classType == ClassType.Form) { project.ProjectItems.AddFromTemplate(@"c:\Program Files (x86)\Microsoft Visual Studio " + dte2.Version + @"\Common7\IDE\ItemTemplates\CSharp\Windows Forms\1033\Form\windowsform.vstemplate", classData.className + ".cs"); } ProjectItem projectItem = null; foreach (ProjectItem pItem in project.ProjectItems) { if (pItem.Name == classData.className + ".cs") { projectItem = pItem; break; } } projectItem.Save(); TextSelection txtsel = (TextSelection)projectItem.Document.Selection; #region Class if (classData.classType == ClassType.Class) { txtsel.GotoLine(9); txtsel.EndOfLine(); if (classData.superClassName != "") { txtsel.Insert(" : " + classData.superClassName); foreach (string interfaceName in classData.interfaceNames) { txtsel.Insert(", " + interfaceName); } } else if (classData.interfaceNames.Count != 0) { txtsel.Insert(" : " + classData.interfaceNames[0]); for (int i = 1; i < classData.interfaceNames.Count; ++i) { txtsel.Insert(", " + classData.interfaceNames[i]); } } } #endregion #region Enum else if (classData.classType == ClassType.Enum) { txtsel.GotoLine(9); txtsel.StartOfLine(); txtsel.CharRight(false, 4); txtsel.DestructiveInsert("enum"); txtsel.Delete(); } #endregion #region Interface else if (classData.classType == ClassType.Interface) { txtsel.GotoLine(9); txtsel.StartOfLine(); txtsel.CharRight(false, 4); txtsel.Insert("interface"); txtsel.Delete(5); } #endregion } } #endregion }