diff --git a/Rubberduck.API/VBA/Parser.cs b/Rubberduck.API/VBA/Parser.cs index 7b24f41100..085287c24c 100644 --- a/Rubberduck.API/VBA/Parser.cs +++ b/Rubberduck.API/VBA/Parser.cs @@ -67,10 +67,10 @@ public interface IParserEvents ] public sealed class Parser : IParser, IDisposable { - private RubberduckParserState _state; - private SynchronousParseCoordinator _parser; - private IVBE _vbe; - private IVBEEvents _vbeEvents; + private readonly RubberduckParserState _state; + private readonly SynchronousParseCoordinator _parser; + private readonly IVBE _vbe; + private readonly IVBEEvents _vbeEvents; private readonly IUiDispatcher _dispatcher; private readonly CancellationTokenSource _tokenSource; @@ -228,6 +228,9 @@ public void Dispose() } _disposed = true; + _parser?.Dispose(); + _vbe?.Dispose(); + _tokenSource.Dispose(); } } } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs index a5aa066e0b..d6d6513285 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs @@ -33,7 +33,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio int annotationLine; //TODO: Make this use the parse tree instead of the code module. - var component = _state.ProjectsProvider.Component(result.QualifiedSelection.QualifiedName); + using (var component = _state.ProjectsProvider.Component(result.QualifiedSelection.QualifiedName)) using (var module = component.CodeModule) { annotationLine = result.QualifiedSelection.Selection.StartLine; diff --git a/Rubberduck.Core/Common/ExportFormatter.cs b/Rubberduck.Core/Common/ExportFormatter.cs index 582348d9eb..66e87ccd01 100644 --- a/Rubberduck.Core/Common/ExportFormatter.cs +++ b/Rubberduck.Core/Common/ExportFormatter.cs @@ -211,215 +211,222 @@ public static MemoryStream XmlSpreadsheetNew(object[][] data, string title, Colu Encoding = new UTF8Encoding(false) }; - var xmlSS = XmlWriter.Create(strm, settings); - - xmlSS.WriteStartDocument(); - - //Processing Instructions - xmlSS.WriteProcessingInstruction("mso-application","progid=\"Excel.Sheet\""); - //Namespaces - xmlSS.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet"); - xmlSS.WriteAttributeString("xmlns", null, null, "urn:schemas-microsoft-com:office:spreadsheet"); - xmlSS.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office"); - xmlSS.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel"); - xmlSS.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet"); - xmlSS.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40"); - - xmlSS.WriteStartElement("Styles"); - - //Default Style - xmlSS.WriteStartElement("Style"); - xmlSS.WriteAttributeString("ss", "ID", null, "Default"); - xmlSS.WriteAttributeString("ss", "Name", null, "Normal"); - xmlSS.WriteStartElement("Alignment"); - xmlSS.WriteAttributeString("ss", "Vertical", null, "Bottom"); - xmlSS.WriteEndElement(); //Close Alignment - xmlSS.WriteStartElement("Font"); - xmlSS.WriteAttributeString("ss", "FontName", null, "Calibri"); - xmlSS.WriteAttributeString("x", "Family", null, "Swiss"); - xmlSS.WriteAttributeString("ss", "Size", null, "11"); - xmlSS.WriteAttributeString("ss", "Color", null, "#000000"); - xmlSS.WriteEndElement(); //Close Font - xmlSS.WriteElementString("Interior", ""); - xmlSS.WriteElementString("NumberFormat", ""); - xmlSS.WriteElementString("Protection", ""); - xmlSS.WriteEndElement(); //Close Style - - //Style for column headers - xmlSS.WriteStartElement("Style"); - xmlSS.WriteAttributeString("ss", "ID", null, "HeaderBottomLeft"); - - xmlSS.WriteStartElement("Alignment"); - xmlSS.WriteAttributeString("ss", "Horizontal", null, "Left"); - xmlSS.WriteAttributeString("ss", "Vertical", null, "Bottom"); - xmlSS.WriteEndElement(); //Close Alignment - - xmlSS.WriteStartElement("Borders"); - - xmlSS.WriteStartElement("Border"); - xmlSS.WriteAttributeString("ss", "Position",null, "Top"); - xmlSS.WriteAttributeString("ss", "LineStyle",null, "Continuous"); - xmlSS.WriteAttributeString("ss", "Weight",null, "1"); - xmlSS.WriteEndElement(); //Close Border - - xmlSS.WriteStartElement("Border"); - xmlSS.WriteAttributeString("ss", "Position",null, "Bottom"); - xmlSS.WriteAttributeString("ss", "LineStyle",null, "Continuous"); - xmlSS.WriteAttributeString("ss", "Weight",null, "1"); - xmlSS.WriteEndElement(); //Close Border - - xmlSS.WriteEndElement(); //Close Borders - - xmlSS.WriteStartElement("Font"); - xmlSS.WriteAttributeString("ss", "Bold", null, "1"); - xmlSS.WriteEndElement(); //Close Font - xmlSS.WriteEndElement(); //Close Style - - //Header_BottomRight - xmlSS.WriteStartElement("Style"); - xmlSS.WriteAttributeString("ss", "ID", null, "HeaderBottomRight"); - - xmlSS.WriteStartElement("Alignment"); - xmlSS.WriteAttributeString("ss", "Horizontal", null, "Right"); - xmlSS.WriteAttributeString("ss", "Vertical", null, "Bottom"); - xmlSS.WriteEndElement(); //Close Alignment - - xmlSS.WriteStartElement("Borders"); - - xmlSS.WriteStartElement("Border"); - xmlSS.WriteAttributeString("ss", "Position", null, "Top"); - xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); - xmlSS.WriteAttributeString("ss", "Weight", null, "1"); - xmlSS.WriteEndElement(); //Close Border - - xmlSS.WriteStartElement("Border"); - xmlSS.WriteAttributeString("ss", "Position", null, "Bottom"); - xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); - xmlSS.WriteAttributeString("ss", "Weight", null, "1"); - xmlSS.WriteEndElement(); //Close Border - - xmlSS.WriteEndElement(); //Close Borders - - xmlSS.WriteStartElement("Font"); - xmlSS.WriteAttributeString("ss", "Bold", null, "1"); - xmlSS.WriteEndElement(); //Close Font - xmlSS.WriteEndElement(); //Close Style - - //Style for last row - xmlSS.WriteStartElement("Style"); - xmlSS.WriteAttributeString("ss", "ID", null, "LastRow"); - xmlSS.WriteStartElement("Borders"); - xmlSS.WriteStartElement("Border"); - xmlSS.WriteAttributeString("ss", "Position", null, "Bottom"); - xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); - xmlSS.WriteAttributeString("ss", "Weight", null, "1"); - xmlSS.WriteEndElement(); //Close Border - xmlSS.WriteEndElement(); //Close Borders - xmlSS.WriteEndElement(); //Close Style - - - //Style for right-aligned data cells - xmlSS.WriteStartElement("Style"); - xmlSS.WriteAttributeString("ss", "ID", null, "RightAligned"); - xmlSS.WriteStartElement("Alignment"); - xmlSS.WriteAttributeString("ss", "Horizontal", null, "Right"); - xmlSS.WriteEndElement(); //Close Alignment - xmlSS.WriteEndElement(); //Close Style - - //Style for right-aligned last row data cells - xmlSS.WriteStartElement("Style"); - xmlSS.WriteAttributeString("ss", "ID", null, "LastRowRightAligned"); - xmlSS.WriteStartElement("Alignment"); - xmlSS.WriteAttributeString("ss", "Horizontal", null, "Right"); - xmlSS.WriteEndElement(); //Close Alignment - xmlSS.WriteStartElement("Borders"); - xmlSS.WriteStartElement("Border"); - xmlSS.WriteAttributeString("ss", "Position", null, "Bottom"); - xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); - xmlSS.WriteAttributeString("ss", "Weight", null, "1"); - xmlSS.WriteEndElement(); //Close Border - xmlSS.WriteEndElement(); //Close Borders - xmlSS.WriteEndElement(); //Close Style - - - xmlSS.WriteEndElement(); //Close Styles - - xmlSS.WriteStartElement("Worksheet"); - xmlSS.WriteAttributeString("ss", "Name", null, "Sheet1"); - xmlSS.WriteStartElement("Table"); - xmlSS.WriteAttributeString("ss", "ExpandedColumnCount", null, columnInfos.Length.ToString()); - xmlSS.WriteAttributeString("ss", "ExpandedRowCount", null, (data.Length + 2).ToString()); - xmlSS.WriteAttributeString("ss", "DefaultRowHeight", null, "15"); - - xmlSS.WriteStartElement("Row"); - xmlSS.WriteStartElement("Cell"); - xmlSS.WriteAttributeString("ss", "MergeAcross", null, (columnInfos.Length-1).ToString()); - xmlSS.WriteStartElement("Data"); - xmlSS.WriteAttributeString("ss", "Type", null, "String"); - xmlSS.WriteValue(title); - xmlSS.WriteEndElement(); //Close Data - xmlSS.WriteEndElement(); //Close Cell - - xmlSS.WriteEndElement(); //Close Row - - //Column Headers - if (columnInfos.Length > 0) - { + using (var xmlSS = XmlWriter.Create(strm, settings)) + { + xmlSS.WriteStartDocument(); + + //Processing Instructions + xmlSS.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\""); + //Namespaces + xmlSS.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet"); + xmlSS.WriteAttributeString("xmlns", null, null, "urn:schemas-microsoft-com:office:spreadsheet"); + xmlSS.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office"); + xmlSS.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel"); + xmlSS.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet"); + xmlSS.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40"); + + xmlSS.WriteStartElement("Styles"); + + //Default Style + xmlSS.WriteStartElement("Style"); + xmlSS.WriteAttributeString("ss", "ID", null, "Default"); + xmlSS.WriteAttributeString("ss", "Name", null, "Normal"); + xmlSS.WriteStartElement("Alignment"); + xmlSS.WriteAttributeString("ss", "Vertical", null, "Bottom"); + xmlSS.WriteEndElement(); //Close Alignment + xmlSS.WriteStartElement("Font"); + xmlSS.WriteAttributeString("ss", "FontName", null, "Calibri"); + xmlSS.WriteAttributeString("x", "Family", null, "Swiss"); + xmlSS.WriteAttributeString("ss", "Size", null, "11"); + xmlSS.WriteAttributeString("ss", "Color", null, "#000000"); + xmlSS.WriteEndElement(); //Close Font + xmlSS.WriteElementString("Interior", ""); + xmlSS.WriteElementString("NumberFormat", ""); + xmlSS.WriteElementString("Protection", ""); + xmlSS.WriteEndElement(); //Close Style + + //Style for column headers + xmlSS.WriteStartElement("Style"); + xmlSS.WriteAttributeString("ss", "ID", null, "HeaderBottomLeft"); + + xmlSS.WriteStartElement("Alignment"); + xmlSS.WriteAttributeString("ss", "Horizontal", null, "Left"); + xmlSS.WriteAttributeString("ss", "Vertical", null, "Bottom"); + xmlSS.WriteEndElement(); //Close Alignment + + xmlSS.WriteStartElement("Borders"); + + xmlSS.WriteStartElement("Border"); + xmlSS.WriteAttributeString("ss", "Position", null, "Top"); + xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); + xmlSS.WriteAttributeString("ss", "Weight", null, "1"); + xmlSS.WriteEndElement(); //Close Border + + xmlSS.WriteStartElement("Border"); + xmlSS.WriteAttributeString("ss", "Position", null, "Bottom"); + xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); + xmlSS.WriteAttributeString("ss", "Weight", null, "1"); + xmlSS.WriteEndElement(); //Close Border + + xmlSS.WriteEndElement(); //Close Borders + + xmlSS.WriteStartElement("Font"); + xmlSS.WriteAttributeString("ss", "Bold", null, "1"); + xmlSS.WriteEndElement(); //Close Font + xmlSS.WriteEndElement(); //Close Style + + //Header_BottomRight + xmlSS.WriteStartElement("Style"); + xmlSS.WriteAttributeString("ss", "ID", null, "HeaderBottomRight"); + + xmlSS.WriteStartElement("Alignment"); + xmlSS.WriteAttributeString("ss", "Horizontal", null, "Right"); + xmlSS.WriteAttributeString("ss", "Vertical", null, "Bottom"); + xmlSS.WriteEndElement(); //Close Alignment + + xmlSS.WriteStartElement("Borders"); + + xmlSS.WriteStartElement("Border"); + xmlSS.WriteAttributeString("ss", "Position", null, "Top"); + xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); + xmlSS.WriteAttributeString("ss", "Weight", null, "1"); + xmlSS.WriteEndElement(); //Close Border + + xmlSS.WriteStartElement("Border"); + xmlSS.WriteAttributeString("ss", "Position", null, "Bottom"); + xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); + xmlSS.WriteAttributeString("ss", "Weight", null, "1"); + xmlSS.WriteEndElement(); //Close Border + + xmlSS.WriteEndElement(); //Close Borders + + xmlSS.WriteStartElement("Font"); + xmlSS.WriteAttributeString("ss", "Bold", null, "1"); + xmlSS.WriteEndElement(); //Close Font + xmlSS.WriteEndElement(); //Close Style + + //Style for last row + xmlSS.WriteStartElement("Style"); + xmlSS.WriteAttributeString("ss", "ID", null, "LastRow"); + xmlSS.WriteStartElement("Borders"); + xmlSS.WriteStartElement("Border"); + xmlSS.WriteAttributeString("ss", "Position", null, "Bottom"); + xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); + xmlSS.WriteAttributeString("ss", "Weight", null, "1"); + xmlSS.WriteEndElement(); //Close Border + xmlSS.WriteEndElement(); //Close Borders + xmlSS.WriteEndElement(); //Close Style + + + //Style for right-aligned data cells + xmlSS.WriteStartElement("Style"); + xmlSS.WriteAttributeString("ss", "ID", null, "RightAligned"); + xmlSS.WriteStartElement("Alignment"); + xmlSS.WriteAttributeString("ss", "Horizontal", null, "Right"); + xmlSS.WriteEndElement(); //Close Alignment + xmlSS.WriteEndElement(); //Close Style + + //Style for right-aligned last row data cells + xmlSS.WriteStartElement("Style"); + xmlSS.WriteAttributeString("ss", "ID", null, "LastRowRightAligned"); + xmlSS.WriteStartElement("Alignment"); + xmlSS.WriteAttributeString("ss", "Horizontal", null, "Right"); + xmlSS.WriteEndElement(); //Close Alignment + xmlSS.WriteStartElement("Borders"); + xmlSS.WriteStartElement("Border"); + xmlSS.WriteAttributeString("ss", "Position", null, "Bottom"); + xmlSS.WriteAttributeString("ss", "LineStyle", null, "Continuous"); + xmlSS.WriteAttributeString("ss", "Weight", null, "1"); + xmlSS.WriteEndElement(); //Close Border + xmlSS.WriteEndElement(); //Close Borders + xmlSS.WriteEndElement(); //Close Style + + + xmlSS.WriteEndElement(); //Close Styles + + xmlSS.WriteStartElement("Worksheet"); + xmlSS.WriteAttributeString("ss", "Name", null, "Sheet1"); + xmlSS.WriteStartElement("Table"); + xmlSS.WriteAttributeString("ss", "ExpandedColumnCount", null, columnInfos.Length.ToString()); + xmlSS.WriteAttributeString("ss", "ExpandedRowCount", null, (data.Length + 2).ToString()); + xmlSS.WriteAttributeString("ss", "DefaultRowHeight", null, "15"); + xmlSS.WriteStartElement("Row"); - foreach (var ch in columnInfos) - { - xmlSS.WriteStartElement("Cell"); - xmlSS.WriteAttributeString("ss", "StyleID", null, "Header" + ch.Heading.VerticalAlignment.ToString() + ch.Heading.HorizontalAlignment.ToString()); - xmlSS.WriteStartElement("Data"); - xmlSS.WriteAttributeString("ss", "Type", null, "String"); - xmlSS.WriteValue(ch.Title); - xmlSS.WriteEndElement(); //Close Data - xmlSS.WriteEndElement(); //Close Cell - } + xmlSS.WriteStartElement("Cell"); + xmlSS.WriteAttributeString("ss", "MergeAcross", null, (columnInfos.Length - 1).ToString()); + xmlSS.WriteStartElement("Data"); + xmlSS.WriteAttributeString("ss", "Type", null, "String"); + xmlSS.WriteValue(title); + xmlSS.WriteEndElement(); //Close Data + xmlSS.WriteEndElement(); //Close Cell + xmlSS.WriteEndElement(); //Close Row - } - for (var r = 0; r < data.Length; r++) - { - xmlSS.WriteStartElement("Row"); - for (var c = 0; c < data[r].Length; c++) + //Column Headers + if (columnInfos.Length > 0) { - var valueType = (data[r][c] is string || data[r][c] == null) ? "String" : "Number"; - xmlSS.WriteStartElement("Cell"); - if (columnInfos[c].Data.HorizontalAlignment == hAlignment.Right) + xmlSS.WriteStartElement("Row"); + foreach (var ch in columnInfos) { - xmlSS.WriteAttributeString("ss", "StyleID", null, (r == data.Length - 1 ? "LastRowRightAligned" : "RightAligned")); + xmlSS.WriteStartElement("Cell"); + xmlSS.WriteAttributeString("ss", "StyleID", null, + "Header" + ch.Heading.VerticalAlignment.ToString() + + ch.Heading.HorizontalAlignment.ToString()); + xmlSS.WriteStartElement("Data"); + xmlSS.WriteAttributeString("ss", "Type", null, "String"); + xmlSS.WriteValue(ch.Title); + xmlSS.WriteEndElement(); //Close Data + xmlSS.WriteEndElement(); //Close Cell } - else + + xmlSS.WriteEndElement(); //Close Row + } + + for (var r = 0; r < data.Length; r++) + { + xmlSS.WriteStartElement("Row"); + for (var c = 0; c < data[r].Length; c++) { - if (r == data.Length - 1) + var valueType = (data[r][c] is string || data[r][c] == null) ? "String" : "Number"; + xmlSS.WriteStartElement("Cell"); + if (columnInfos[c].Data.HorizontalAlignment == hAlignment.Right) { - xmlSS.WriteAttributeString("ss", "StyleID", null, "LastRow"); + xmlSS.WriteAttributeString("ss", "StyleID", null, + (r == data.Length - 1 ? "LastRowRightAligned" : "RightAligned")); + } + else + { + if (r == data.Length - 1) + { + xmlSS.WriteAttributeString("ss", "StyleID", null, "LastRow"); + } } - } - xmlSS.WriteStartElement("Data"); - xmlSS.WriteAttributeString("ss", "Type", null, valueType); - if (data[r][c] != null) - { - xmlSS.WriteValue(data[r][c].ToString()); + xmlSS.WriteStartElement("Data"); + + xmlSS.WriteAttributeString("ss", "Type", null, valueType); + if (data[r][c] != null) + { + xmlSS.WriteValue(data[r][c].ToString()); + } + + xmlSS.WriteEndElement(); //Close Data + xmlSS.WriteEndElement(); //Close Cell } - xmlSS.WriteEndElement(); //Close Data - xmlSS.WriteEndElement(); //Close Cell + + xmlSS.WriteEndElement(); //Close Row } - xmlSS.WriteEndElement(); //Close Row - } - xmlSS.WriteEndElement(); //Close Table - xmlSS.WriteEndElement(); //Close Worksheet - xmlSS.WriteEndElement(); //Close Workbook - xmlSS.WriteEndDocument(); - xmlSS.Close(); + xmlSS.WriteEndElement(); //Close Table + xmlSS.WriteEndElement(); //Close Worksheet + xmlSS.WriteEndElement(); //Close Workbook + xmlSS.WriteEndDocument(); + xmlSS.Close(); - return strm; + return strm; + } } - - + public static string RTF(object[][] data, string title) { const byte fontSize = 16; //half-points diff --git a/Rubberduck.Core/Common/WindowsOperatingSystem.cs b/Rubberduck.Core/Common/WindowsOperatingSystem.cs index c818b85d55..ed811f32e8 100644 --- a/Rubberduck.Core/Common/WindowsOperatingSystem.cs +++ b/Rubberduck.Core/Common/WindowsOperatingSystem.cs @@ -11,7 +11,8 @@ public void ShowFolder(string folderPath) { Directory.CreateDirectory(folderPath); } - Process.Start(folderPath); + + using (Process.Start(folderPath)) { } } } } diff --git a/Rubberduck.Core/UI/CodeExplorer/Commands/AddMDIFormCommand.cs b/Rubberduck.Core/UI/CodeExplorer/Commands/AddMDIFormCommand.cs index 10b634bf53..2761ce5d21 100644 --- a/Rubberduck.Core/UI/CodeExplorer/Commands/AddMDIFormCommand.cs +++ b/Rubberduck.Core/UI/CodeExplorer/Commands/AddMDIFormCommand.cs @@ -45,14 +45,17 @@ private bool EvaluateCanExecuteCore(IVBProject project, CodeExplorerItemViewMode return false; } - foreach (var component in project.VBComponents) + using (var components = project.VBComponents) { - using (component) + foreach (var component in components) { - if (component.Type == ComponentType.MDIForm) + using (component) { - // Only one MDI Form allowed per project - return false; + if (component.Type == ComponentType.MDIForm) + { + // Only one MDI Form allowed per project + return false; + } } } } diff --git a/Rubberduck.Core/UI/CodeExplorer/Commands/CopyResultsCommand.cs b/Rubberduck.Core/UI/CodeExplorer/Commands/CopyResultsCommand.cs index c1f0c0da20..893e6f356d 100644 --- a/Rubberduck.Core/UI/CodeExplorer/Commands/CopyResultsCommand.cs +++ b/Rubberduck.Core/UI/CodeExplorer/Commands/CopyResultsCommand.cs @@ -22,22 +22,23 @@ public CopyResultsCommand(RubberduckParserState state) : base(LogManager.GetCurr protected override void OnExecute(object parameter) { - const string XML_SPREADSHEET_DATA_FORMAT = "XML Spreadsheet"; + const string XML_SPREADSHEET_DATA_FORMAT = "XML Spreadsheet"; - ColumnInfo[] ColumnInfos = { new ColumnInfo("Project"), new ColumnInfo("Folder"), new ColumnInfo("Component"), new ColumnInfo("Declaration Type"), new ColumnInfo("Scope"), - new ColumnInfo("Name"), new ColumnInfo("Return Type") }; + ColumnInfo[] ColumnInfos = { new ColumnInfo("Project"), new ColumnInfo("Folder"), new ColumnInfo("Component"), new ColumnInfo("Declaration Type"), new ColumnInfo("Scope"), + new ColumnInfo("Name"), new ColumnInfo("Return Type") }; - // this.ProjectName, this.CustomFolder, this.ComponentName, this.DeclarationType.ToString(), this.Scope - var aDeclarations = _state.AllUserDeclarations.Select(declaration => declaration.ToArray()).ToArray(); + // this.ProjectName, this.CustomFolder, this.ComponentName, this.DeclarationType.ToString(), this.Scope + var aDeclarations = _state.AllUserDeclarations.Select(declaration => declaration.ToArray()).ToArray(); - const string resource = "Rubberduck User Declarations - {0}"; - var title = string.Format(resource, DateTime.Now.ToString(CultureInfo.InvariantCulture)); - - var csvResults = ExportFormatter.Csv(aDeclarations, title, ColumnInfos); - var htmlResults = ExportFormatter.HtmlClipboardFragment(aDeclarations, title, ColumnInfos); - var rtfResults = ExportFormatter.RTF(aDeclarations, title); + const string resource = "Rubberduck User Declarations - {0}"; + var title = string.Format(resource, DateTime.Now.ToString(CultureInfo.InvariantCulture)); + + var csvResults = ExportFormatter.Csv(aDeclarations, title, ColumnInfos); + var htmlResults = ExportFormatter.HtmlClipboardFragment(aDeclarations, title, ColumnInfos); + var rtfResults = ExportFormatter.RTF(aDeclarations, title); - var strm1 = ExportFormatter.XmlSpreadsheetNew(aDeclarations, title, ColumnInfos); + using (var strm1 = ExportFormatter.XmlSpreadsheetNew(aDeclarations, title, ColumnInfos)) + { //Add the formats from richest formatting to least formatting _clipboard.AppendStream(DataFormats.GetDataFormat(XML_SPREADSHEET_DATA_FORMAT).Name, strm1); _clipboard.AppendString(DataFormats.Rtf, rtfResults); @@ -45,6 +46,7 @@ protected override void OnExecute(object parameter) _clipboard.AppendString(DataFormats.CommaSeparatedValue, csvResults); _clipboard.Flush(); + } } } } \ No newline at end of file diff --git a/Rubberduck.Core/UI/CodeExplorer/Commands/PrintCommand.cs b/Rubberduck.Core/UI/CodeExplorer/Commands/PrintCommand.cs index 25cf892199..222bc044a8 100644 --- a/Rubberduck.Core/UI/CodeExplorer/Commands/PrintCommand.cs +++ b/Rubberduck.Core/UI/CodeExplorer/Commands/PrintCommand.cs @@ -87,19 +87,23 @@ protected override void OnExecute(object parameter) { while (index < text.Count) { - var font = new Font(new FontFamily("Consolas"), 10, FontStyle.Regular); - printPageArgs.Graphics.DrawString(text[index++], font, Brushes.Black, 0, offsetY, new StringFormat()); + using (var font = new Font(new FontFamily("Consolas"), 10, FontStyle.Regular)) + using (var stringFormat = new StringFormat()) + { + printPageArgs.Graphics.DrawString(text[index++], font, Brushes.Black, 0, offsetY, + stringFormat); - offsetY += font.Height; + offsetY += font.Height; - if (offsetY >= pageHeight) - { - printPageArgs.HasMorePages = true; - offsetY = 0; - return; - } + if (offsetY >= pageHeight) + { + printPageArgs.HasMorePages = true; + offsetY = 0; + return; + } - printPageArgs.HasMorePages = false; + printPageArgs.HasMorePages = false; + } } }; diff --git a/Rubberduck.Core/UI/Command/ExportAllCommand.cs b/Rubberduck.Core/UI/Command/ExportAllCommand.cs index bcdac6e99b..97d2c70fe5 100644 --- a/Rubberduck.Core/UI/Command/ExportAllCommand.cs +++ b/Rubberduck.Core/UI/Command/ExportAllCommand.cs @@ -61,12 +61,27 @@ private bool Evaluate(IVBProject project) protected override void OnExecute(object parameter) { - var projectNode = parameter as CodeExplorerProjectViewModel; - - var vbproject = parameter as IVBProject; + switch (parameter) + { + case CodeExplorerProjectViewModel projectNode when projectNode.Declaration.Project != null: + Export(projectNode.Declaration.Project); + break; + case IVBProject vbproject: + Export(vbproject); + break; + default: + { + using (var project = _vbe.ActiveVBProject) + { + Export(project); + } + break; + } + } + } - var project = projectNode?.Declaration.Project ?? vbproject ?? _vbe.ActiveVBProject; - + private void Export(IVBProject project) + { var desc = string.Format(RubberduckUI.ExportAllCommand_SaveAsDialog_Title, project.Name); // If .GetDirectoryName is passed an empty string for a RootFolder, diff --git a/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs b/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs index 7ca3cb5997..3031f2087b 100644 --- a/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs +++ b/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs @@ -232,32 +232,47 @@ private Declaration FindFormDesignerTarget(QualifiedModuleName? qualifiedModuleN { projectId = activeProject.ProjectId; } - var component = _vbe.SelectedVBComponent; - if (component?.HasDesigner ?? false) + using (var component = _vbe.SelectedVBComponent) { - DeclarationType selectedType; - string selectedName; - using (var selectedControls = component.SelectedControls) + if (component?.HasDesigner ?? false) { - var selectedCount = selectedControls.Count; - if (selectedCount > 1) + DeclarationType selectedType; + string selectedName; + using (var selectedControls = component.SelectedControls) { - return null; + var selectedCount = selectedControls.Count; + if (selectedCount > 1) + { + return null; + } + + (selectedType, selectedName) = GetSelectedName(component, selectedControls, selectedCount); } - // Cannot use DeclarationType.UserForm, parser only assigns UserForms the ClassModule flag - (selectedType, selectedName) = selectedCount == 0 - ? (DeclarationType.ClassModule, component.Name) - : (DeclarationType.Control, selectedControls[0].Name); + return _state.DeclarationFinder + .MatchName(selectedName) + .SingleOrDefault(m => m.ProjectId == projectId + && m.DeclarationType.HasFlag(selectedType) + && m.ComponentName == component.Name); } - return _state.DeclarationFinder - .MatchName(selectedName) - .SingleOrDefault(m => m.ProjectId == projectId - && m.DeclarationType.HasFlag(selectedType) - && m.ComponentName == component.Name); + + return null; + } + } + + private static (DeclarationType, string Name) GetSelectedName(IVBComponent component, IControls selectedControls, int selectedCount) + { + // Cannot use DeclarationType.UserForm, parser only assigns UserForms the ClassModule flag + if (selectedCount == 0) + { + return (DeclarationType.ClassModule, component.Name); + } + + using (var firstSelectedControl = selectedControls[0]) + { + return (DeclarationType.Control, firstSelectedControl.Name); } - return null; } private Declaration FindFormDesignerTarget(QualifiedModuleName qualifiedModuleName) diff --git a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs index 63cd0e9160..ff67c2ff84 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs @@ -169,8 +169,27 @@ public void EvaluateCanExecute(RubberduckParserState state) } } - public ICommandBars Parent { get; set; } - public ICommandBar Item { get; private set; } + private ICommandBars _parent; + public ICommandBars Parent + { + get => _parent; + set + { + _parent?.Dispose(); + _parent = value; + } + } + + private ICommandBar _item; + public ICommandBar Item + { + get => _item; + private set + { + _item?.Dispose(); + _item = value; + } + } public void RemoveCommandBar() { @@ -181,9 +200,9 @@ public void RemoveCommandBar() Logger.Debug("Removing commandbar."); RemoveChildren(); Item.Delete(); - Item.Dispose(); + + // Setting them to null will automatically dispose those Item = null; - Parent?.Dispose(); Parent = null; } } diff --git a/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs b/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs index 8b6e4b75a7..713a256f24 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs @@ -24,8 +24,27 @@ protected ParentMenuItemBase(string key, IEnumerable items, int? befo _items = items.ToDictionary(item => item, item => null as ICommandBarControl); } - public ICommandBarControls Parent { get; set; } - public ICommandBarPopup Item { get; private set; } + private ICommandBarControls _parent; + public ICommandBarControls Parent + { + get => _parent; + set + { + _parent?.Dispose(); + _parent = value; + } + } + + private ICommandBarPopup _item; + public ICommandBarPopup Item + { + get => _item; + private set + { + _item?.Dispose(); + _item = value; + } + } public string Key => Item?.Tag; @@ -91,7 +110,8 @@ public void RemoveMenu() Logger.Debug($"Removing menu {_key}."); RemoveChildren(); Item?.Delete(); - Item?.Dispose(); + + //This will also dispose the Item as well Item = null; } diff --git a/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs index 2ddc7c35d7..629b8b8082 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs @@ -59,7 +59,7 @@ protected override void OnExecute(object parameter) } else { - target = _state.FindSelectedDeclaration(Vbe.ActiveCodePane); + target = _state.FindSelectedDeclaration(activePane); } } diff --git a/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs b/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs index 67d2bb3ff8..7fbdd570ab 100644 --- a/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs +++ b/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs @@ -125,13 +125,13 @@ private string DeclarationFormatFor(string declarationFormat, string type, IUnit private IVBProject GetProject() { - var activeProject = _vbe.ActiveVBProject; - if (!activeProject.IsWrappingNullReference) + using (var activeProject = _vbe.ActiveVBProject) { - return activeProject; + if (!activeProject.IsWrappingNullReference) + { + return activeProject; + } } - - activeProject.Dispose(); using (var projects = _vbe.VBProjects) { @@ -158,100 +158,115 @@ protected override void OnExecute(object parameter) { var parameterIsModuleDeclaration = parameter is ProceduralModuleDeclaration || parameter is ClassModuleDeclaration; - using (var project = parameter as IVBProject ?? - (parameterIsModuleDeclaration ? ((Declaration) parameter).Project : GetProject())) + switch(parameter) { - if (project == null || project.IsWrappingNullReference) - { - return; - } + case IVBProject project: + ExecuteInternal(project, null); + break; + case Declaration declaration when parameterIsModuleDeclaration: + ExecuteInternal(declaration.Project, declaration); + break; + default: + using (var project = GetProject()) + { + ExecuteInternal(project, null); + } + break; + } + } - var settings = _configLoader.LoadConfiguration().UserSettings.UnitTestSettings; + private void ExecuteInternal(IVBProject project, Declaration projectDeclaration) + { + if (project == null || project.IsWrappingNullReference) + { + return; + } - if (settings.BindingMode == BindingMode.EarlyBinding) - { - // FIXME: Push the actual adding of TestModules into UnitTesting, which sidesteps VBEInteraction being inaccessble here - _interaction.EnsureProjectReferencesUnitTesting(project); - } + var settings = _configLoader.LoadConfiguration().UserSettings.UnitTestSettings; + + if (settings.BindingMode == BindingMode.EarlyBinding) + { + // FIXME: Push the actual adding of TestModules into UnitTesting, which sidesteps VBEInteraction being inaccessble here + _interaction.EnsureProjectReferencesUnitTesting(project); + } - try + try + { + using (var components = project.VBComponents) { - using (var components = project.VBComponents) + using (var component = components.Add(ComponentType.StandardModule)) { - using (var component = components.Add(ComponentType.StandardModule)) + using (var module = component.CodeModule) { - using (var module = component.CodeModule) + component.Name = GetNextTestModuleName(project); + + var hasOptionExplicit = false; + if (module.CountOfLines > 0 && module.CountOfDeclarationLines > 0) { - component.Name = GetNextTestModuleName(project); + hasOptionExplicit = module.GetLines(1, module.CountOfDeclarationLines) + .Contains("Option Explicit"); + } - var hasOptionExplicit = false; - if (module.CountOfLines > 0 && module.CountOfDeclarationLines > 0) - { - hasOptionExplicit = module.GetLines(1, module.CountOfDeclarationLines) - .Contains("Option Explicit"); - } + var options = string.Concat(hasOptionExplicit ? string.Empty : "Option Explicit\r\n", + "Option Private Module\r\n\r\n"); - var options = string.Concat(hasOptionExplicit ? string.Empty : "Option Explicit\r\n", - "Option Private Module\r\n\r\n"); + if (projectDeclaration != null) + { + var moduleCodeBuilder = new StringBuilder(); + var declarationsToStub = GetDeclarationsToStub(projectDeclaration); - if (parameterIsModuleDeclaration) + foreach (var declaration in declarationsToStub) { - var moduleCodeBuilder = new StringBuilder(); - var declarationsToStub = GetDeclarationsToStub((Declaration) parameter); + var name = string.Empty; - foreach (var declaration in declarationsToStub) + switch (declaration.DeclarationType) { - var name = string.Empty; - - switch (declaration.DeclarationType) - { - case DeclarationType.Procedure: - case DeclarationType.Function: - name = declaration.IdentifierName; - break; - case DeclarationType.PropertyGet: - name = $"Get{declaration.IdentifierName}"; - break; - case DeclarationType.PropertyLet: - name = $"Let{declaration.IdentifierName}"; - break; - case DeclarationType.PropertySet: - name = $"Set{declaration.IdentifierName}"; - break; - } - - var stub = AddTestMethodCommand.TestMethodTemplate.Replace( - AddTestMethodCommand.NamePlaceholder, $"{name}_Test"); - moduleCodeBuilder.AppendLine(stub); + case DeclarationType.Procedure: + case DeclarationType.Function: + name = declaration.IdentifierName; + break; + case DeclarationType.PropertyGet: + name = $"Get{declaration.IdentifierName}"; + break; + case DeclarationType.PropertyLet: + name = $"Let{declaration.IdentifierName}"; + break; + case DeclarationType.PropertySet: + name = $"Set{declaration.IdentifierName}"; + break; } - module.AddFromString(options + GetTestModule(settings) + moduleCodeBuilder); + var stub = AddTestMethodCommand.TestMethodTemplate.Replace( + AddTestMethodCommand.NamePlaceholder, $"{name}_Test"); + moduleCodeBuilder.AppendLine(stub); } - else - { - var defaultTestMethod = settings.DefaultTestStubInNewModule - ? AddTestMethodCommand.TestMethodTemplate.Replace( - AddTestMethodCommand.NamePlaceholder, - "TestMethod1") - : string.Empty; - module.AddFromString(options + GetTestModule(settings) + defaultTestMethod); - } + module.AddFromString(options + GetTestModule(settings) + moduleCodeBuilder); } + else + { + var defaultTestMethod = settings.DefaultTestStubInNewModule + ? AddTestMethodCommand.TestMethodTemplate.Replace( + AddTestMethodCommand.NamePlaceholder, + "TestMethod1") + : string.Empty; - component.Activate(); + module.AddFromString(options + GetTestModule(settings) + defaultTestMethod); + } } + + component.Activate(); } } - catch (Exception ex) - { - _messageBox.Message(TestExplorer.Command_AddTestModule_Error); - Logger.Warn("Unable to add test module. An exception was thrown."); - Logger.Warn(ex); - } - - _state.OnParseRequested(this); } + catch (Exception ex) + { + _messageBox.Message(TestExplorer.Command_AddTestModule_Error); + Logger.Warn("Unable to add test module. An exception was thrown."); + Logger.Warn(ex); + } + + _state.OnParseRequested(this); } // FIXME push this into Rubberduck.UnitTesting assembly diff --git a/Rubberduck.Core/UI/UnitTesting/TestExplorerViewModel.cs b/Rubberduck.Core/UI/UnitTesting/TestExplorerViewModel.cs index 7dc2276436..8d85542a48 100644 --- a/Rubberduck.Core/UI/UnitTesting/TestExplorerViewModel.cs +++ b/Rubberduck.Core/UI/UnitTesting/TestExplorerViewModel.cs @@ -236,15 +236,17 @@ private void ExecuteCopyResultsCommand(object parameter) var htmlResults = ExportFormatter.HtmlClipboardFragment(aResults, title, columnInfos); var rtfResults = ExportFormatter.RTF(aResults, title); - var strm1 = ExportFormatter.XmlSpreadsheetNew(aResults, title, columnInfos); - //Add the formats from richest formatting to least formatting - _clipboard.AppendStream(DataFormats.GetDataFormat(XML_SPREADSHEET_DATA_FORMAT).Name, strm1); - _clipboard.AppendString(DataFormats.Rtf, rtfResults); - _clipboard.AppendString(DataFormats.Html, htmlResults); - _clipboard.AppendString(DataFormats.CommaSeparatedValue, csvResults); - //_clipboard.AppendString(DataFormats.UnicodeText, textResults); - - _clipboard.Flush(); + using (var strm1 = ExportFormatter.XmlSpreadsheetNew(aResults, title, columnInfos)) + { + //Add the formats from richest formatting to least formatting + _clipboard.AppendStream(DataFormats.GetDataFormat(XML_SPREADSHEET_DATA_FORMAT).Name, strm1); + _clipboard.AppendString(DataFormats.Rtf, rtfResults); + _clipboard.AppendString(DataFormats.Html, htmlResults); + _clipboard.AppendString(DataFormats.CommaSeparatedValue, csvResults); + //_clipboard.AppendString(DataFormats.UnicodeText, textResults); + + _clipboard.Flush(); + } } private void ExecuteRunSelectedCategoryTestsCommand(object obj) diff --git a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs index 71a6a992c9..ddc0e1c9f4 100644 --- a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs +++ b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs @@ -67,37 +67,51 @@ public void EnsureProjectReferencesUnitTesting(IVBProject project) if (project == null || project.IsWrappingNullReference) { return; } var libFolder = IntPtr.Size == 8 ? "win64" : "win32"; const string libGuid = RubberduckGuid.RubberduckTypeLibGuid; - var pathKey = Registry.ClassesRoot.OpenSubKey($@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}\0\{libFolder}"); + var pathKey = Registry.ClassesRoot.OpenSubKey( + $@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}\0\{libFolder}"); - var referencePath = pathKey?.GetValue(string.Empty, string.Empty) as string; - string name = null; - - if (!string.IsNullOrWhiteSpace(referencePath)) + if (pathKey != null) { - var tlbKey = - Registry.ClassesRoot.OpenSubKey($@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}"); - - name = tlbKey?.GetValue(string.Empty, string.Empty) as string; - } + var referencePath = pathKey.GetValue(string.Empty, string.Empty) as string; + string name = null; - if (string.IsNullOrWhiteSpace(referencePath) || string.IsNullOrWhiteSpace(name)) - { - throw new InvalidOperationException("Cannot locate the tlb in the registry or the entry may be corrupted. Therefore early binding is not possible"); - } + if (!string.IsNullOrWhiteSpace(referencePath)) + { + var tlbKey = + Registry.ClassesRoot.OpenSubKey( + $@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}"); + + if(tlbKey != null) + { + name = tlbKey.GetValue(string.Empty, string.Empty) as string; + tlbKey.Dispose(); + } + } - using (var references = project.References) - { - var reference = FindReferenceByName(references, name); - if (reference != null) + if (string.IsNullOrWhiteSpace(referencePath) || string.IsNullOrWhiteSpace(name)) { - references.Remove(reference); - reference.Dispose(); + throw new InvalidOperationException( + "Cannot locate the tlb in the registry or the entry may be corrupted. Therefore early binding is not possible"); } - if (!ReferenceWithPathExists(references, referencePath)) + using (var references = project.References) { - references.AddFromFile(referencePath); + var reference = FindReferenceByName(references, name); + if (reference != null) + { + references.Remove(reference); + reference.Dispose(); + } + + if (!ReferenceWithPathExists(references, referencePath)) + { + // AddFromFile returns a new wrapped reference so we must + // ensure it is disposed properly. + using (references.AddFromFile(referencePath)) { } + } } + + pathKey.Dispose(); } } diff --git a/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs b/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs index 60fe688249..52b48626bc 100644 --- a/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs +++ b/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs @@ -89,7 +89,7 @@ private struct TraceData /// private const int StackTraceNumberOfElementsToSkipOnRemoval = 6; private const int StackTrackNumberOfElementsToSkipOnAddUpdate = 8; - private const int StackTraceDepth = 5; + private const int StackTraceDepth = 10; /// public void Serialize(string targetDirectory) diff --git a/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeInfos.cs b/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeInfos.cs index f2168721a9..c7afea6e7b 100644 --- a/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeInfos.cs +++ b/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeInfos.cs @@ -464,8 +464,8 @@ private void InitCommon() { // We have to wrap the ITypeLib returned by GetContainingTypeLib // so we cast to our ITypeInfo_Ptrs interface in order to work with the raw IntPtrs - IntPtr typeLibPtr = IntPtr.Zero; - ((ITypeInfo_Ptrs)target_ITypeInfo).GetContainingTypeLib(out typeLibPtr, out _containerTypeLibIndex); + ((ITypeInfo_Ptrs)target_ITypeInfo).GetContainingTypeLib(out var typeLibPtr, out _containerTypeLibIndex); + _containerTypeLib?.Dispose(); _containerTypeLib = new TypeLibWrapper(typeLibPtr, true); } catch (Exception e) @@ -718,10 +718,11 @@ public TypeInfoWrapper GetControlType(string controlName) public TypeInfoWrapper GetSafeRefTypeInfo(int hRef) { - IntPtr typeInfoPtr = IntPtr.Zero; // we cast to our ITypeInfo_Ptrs interface in order to work with the raw IntPtr for aggregation - ((ITypeInfo_Ptrs)target_ITypeInfo).GetRefTypeInfo(hRef, out typeInfoPtr); + ((ITypeInfo_Ptrs)target_ITypeInfo).GetRefTypeInfo(hRef, out var typeInfoPtr); var outVal = new TypeInfoWrapper(typeInfoPtr, _isUserFormBaseClass ? (int?)hRef : null); // takes ownership of the COM reference + + _typeInfosWrapped?.Dispose(); _typeInfosWrapped = _typeInfosWrapped ?? new DisposableList(); _typeInfosWrapped.Add(outVal); return outVal; @@ -729,7 +730,7 @@ public TypeInfoWrapper GetSafeRefTypeInfo(int hRef) public TypeInfoWrapper GetSafeImplementedTypeInfo(int index) { - target_ITypeInfo.GetRefTypeOfImplType(index, out int href); + target_ITypeInfo.GetRefTypeOfImplType(index, out var href); return GetSafeRefTypeInfo(href); } diff --git a/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeLibs.cs b/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeLibs.cs index 7fabe553ea..0a62349a81 100644 --- a/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeLibs.cs +++ b/Rubberduck.VBEEditor/ComManagement/TypeLibs/TypeLibs.cs @@ -218,10 +218,10 @@ public void Dispose() public TypeInfoWrapper GetSafeTypeInfoByIndex(int index) { - IntPtr typeInfoPtr = IntPtr.Zero; // We cast to our IVBETypeLib interface in order to work with the raw IntPtr for aggregation - ((ITypeLib_Ptrs)target_ITypeLib).GetTypeInfo(index, out typeInfoPtr); + ((ITypeLib_Ptrs)target_ITypeLib).GetTypeInfo(index, out var typeInfoPtr); var outVal = new TypeInfoWrapper(typeInfoPtr); + _typeInfosWrapped?.Dispose(); _typeInfosWrapped = _typeInfosWrapped ?? new DisposableList(); _typeInfosWrapped.Add(outVal); return outVal; @@ -382,13 +382,15 @@ public void Document(StringLineBuilder output) // so we cast to our IVBETypeLib interface in order to work with the raw IntPtr for aggregation void ComTypes.ITypeLib.GetTypeInfoOfGuid(ref Guid guid, out ComTypes.ITypeInfo ppTInfo) { - IntPtr typeInfoPtr = IntPtr.Zero; - ((ITypeLib_Ptrs)target_ITypeLib).GetTypeInfoOfGuid(guid, out typeInfoPtr); - var outVal = new TypeInfoWrapper(typeInfoPtr); // takes ownership of the COM reference - ppTInfo = outVal; + ((ITypeLib_Ptrs)target_ITypeLib).GetTypeInfoOfGuid(guid, out var typeInfoPtr); + using (var outVal = new TypeInfoWrapper(typeInfoPtr)) // takes ownership of the COM reference + { + ppTInfo = outVal; - _typeInfosWrapped = _typeInfosWrapped ?? new DisposableList(); - _typeInfosWrapped.Add(outVal); + _typeInfosWrapped?.Dispose(); + _typeInfosWrapped = _typeInfosWrapped ?? new DisposableList(); + _typeInfosWrapped.Add(outVal); + } } void ComTypes.ITypeLib.GetTypeInfo(int index, out ComTypes.ITypeInfo ppTI) => ppTI = GetSafeTypeInfoByIndex(index); // We have to wrap the ITypeInfo returned by GetTypeInfo diff --git a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs index a5dbc8515f..387f58e1ea 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs @@ -102,17 +102,22 @@ private void ForceFocus() Show(); - var window = VBE.MainWindow; - var mainWindowHandle = window.Handle(); - var handle = window.Handle().FindChildWindow(Window.Caption); - - if (handle != IntPtr.Zero) - { - NativeMethods.ActivateWindow(handle, mainWindowHandle); - } - else + using (var vbe = VBE) + using (var mainWindow = vbe.MainWindow) + using (var window = Window) { - System.Diagnostics.Debug.WriteLine("CodePane.ForceFocus() failed to get a handle on the MainWindow."); + var mainWindowHandle = mainWindow.Handle(); + var handle = mainWindow.Handle().FindChildWindow(window.Caption); + + if (handle != IntPtr.Zero) + { + NativeMethods.ActivateWindow(handle, mainWindowHandle); + } + else + { + _logger.Debug( + "CodePane.ForceFocus() failed to get a handle on the MainWindow."); + } } } diff --git a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProject.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProject.cs index 10d2c7379c..ed0af57dc4 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProject.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProject.cs @@ -129,7 +129,19 @@ public override int GetHashCode() public IReadOnlyList ComponentNames() { - return VBComponents.Select(component => component.Name).ToArray(); + var names = new List(); + using (var components = VBComponents) + { + foreach (var component in components) + { + using (component) + { + names.Add(component.Name); + } + } + + return names.ToArray(); + } } public void AssignProjectId() diff --git a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs index 1edc45584b..3a4355e4d5 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs @@ -92,23 +92,23 @@ void VB._dispVBProjectsEvents.ItemRemoved([MarshalAs(UnmanagedType.Interface), I void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), In] VB.VBProject VBProject, [MarshalAs(UnmanagedType.BStr), In] string OldName) { - var project = new VBProject(VBProject); - - if (!IsInDesignMode()) + using (var project = new VBProject(VBProject)) { - project.Dispose(); - return; - } + if (!IsInDesignMode()) + { + return; + } + + var projectId = project.ProjectId; - var projectId = project.ProjectId; + if (projectId == null) + { + return; + } - var handler = ProjectRenamed; - if (handler == null || projectId == null) - { - project.Dispose(); - return; + var handler = ProjectRenamed; + handler?.Invoke(this, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } - handler.Invoke(project, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } public event EventHandler ProjectActivated; @@ -124,7 +124,6 @@ private void OnDispatch(EventHandler dispatched, VB.VBProject var handler = dispatched; if (handler == null || !IsInDesignMode()) { - project.Dispose(); return; } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs index 85a9b60a73..86f4efe4d3 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs @@ -12,6 +12,7 @@ public FallbackApp(IVBE vbe) public string ApplicationName => "(unknown)"; public IEnumerable GetDocuments() => null; public HostDocument GetDocument(QualifiedModuleName moduleName) => null; + public void Dispose() { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs index 07e56869f4..99498a89a7 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs @@ -102,17 +102,22 @@ private void ForceFocus() Show(); - var window = VBE.MainWindow; - var mainWindowHandle = window.Handle(); - var handle = window.Handle().FindChildWindow(Window.Caption); - - if (handle != IntPtr.Zero) + using (var vbe = VBE) + using (var mainWindow = vbe.MainWindow) + using (var window = Window) { - NativeMethods.ActivateWindow(handle, mainWindowHandle); - } - else - { - System.Diagnostics.Debug.WriteLine("CodePane.ForceFocus() failed to get a handle on the MainWindow."); + var mainWindowHandle = mainWindow.Handle(); + var handle = mainWindow.Handle().FindChildWindow(window.Caption); + + if (handle != IntPtr.Zero) + { + NativeMethods.ActivateWindow(handle, mainWindowHandle); + } + else + { + _logger.Debug( + "CodePane.ForceFocus() failed to get a handle on the MainWindow."); + } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs index 4d17a62ab3..f9d0caa8af 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs @@ -195,66 +195,64 @@ public IHostApplication HostApplication() } //Guessing the above will work like 99.9999% of the time for supported applications. - var project = ActiveVBProject; + using (var project = ActiveVBProject) { if (project.IsWrappingNullReference) { const int ctlViewHost = 106; - var commandBars = CommandBars; - var hostAppControl = commandBars.FindControl(ControlType.Button, ctlViewHost); + using (var commandBars = CommandBars) { - - IHostApplication result; - if (hostAppControl.IsWrappingNullReference) - { - result = null; - } - else + var hostAppControl = commandBars.FindControl(ControlType.Button, ctlViewHost); { - switch (hostAppControl.Caption) + IHostApplication result; + if (hostAppControl.IsWrappingNullReference) { - case "Microsoft Excel": - result = new ExcelApp(this); - break; - case "Microsoft Access": - result = new AccessApp(this); - break; - case "Microsoft Word": - result = new WordApp(this); - break; - case "Microsoft PowerPoint": - result = new PowerPointApp(this); - break; - case "Microsoft Outlook": - result = new OutlookApp(this); - break; - case "Microsoft Project": - result = new ProjectApp(this); - break; - case "Microsoft Publisher": - result = new PublisherApp(this); - break; - case "Microsoft Visio": - result = new VisioApp(this); - break; - case "AutoCAD": - result = new AutoCADApp(this); - break; - case "CorelDRAW": - result = new CorelDRAWApp(this); - break; - case "SolidWorks": - result = new SolidWorksApp(this); - break; - default: - result = null; - break; + result = null; + } + else + { + switch (hostAppControl.Caption) + { + case "Microsoft Excel": + result = new ExcelApp(this); + break; + case "Microsoft Access": + result = new AccessApp(this); + break; + case "Microsoft Word": + result = new WordApp(this); + break; + case "Microsoft PowerPoint": + result = new PowerPointApp(this); + break; + case "Microsoft Outlook": + result = new OutlookApp(this); + break; + case "Microsoft Project": + result = new ProjectApp(this); + break; + case "Microsoft Publisher": + result = new PublisherApp(this); + break; + case "Microsoft Visio": + result = new VisioApp(this); + break; + case "AutoCAD": + result = new AutoCADApp(this); + break; + case "CorelDRAW": + result = new CorelDRAWApp(this); + break; + case "SolidWorks": + result = new SolidWorksApp(this); + break; + default: + result = null; + break; + } } } - - _host = result; - return result; } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs index 05601067e7..2b2368245a 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs @@ -100,7 +100,19 @@ public override int GetHashCode() public IReadOnlyList ComponentNames() { - return VBComponents.Select(component => component.Name).ToArray(); + var names = new List(); + using (var components = VBComponents) + { + foreach (var component in components) + { + using (component) + { + names.Add(component.Name); + } + } + + return names.ToArray(); + } } public void AssignProjectId() @@ -174,9 +186,9 @@ public string ProjectDisplayName return _displayName; } - var vbe = VBE; - var activeProject = vbe.ActiveVBProject; - var mainWindow = vbe.MainWindow; + using (var vbe = VBE) + using (var activeProject = vbe.ActiveVBProject) + using (var mainWindow = vbe.MainWindow) { try { diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs index 1f066722c2..8fd7c9ada1 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs @@ -96,23 +96,23 @@ void VB._dispVBProjectsEvents.ItemRemoved([MarshalAs(UnmanagedType.Interface), I void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), In] VB.VBProject VBProject, [MarshalAs(UnmanagedType.BStr), In] string OldName) { - var project = new VBProject(VBProject); - - if (!IsInDesignMode() || VBProject.Protection == VB.vbext_ProjectProtection.vbext_pp_locked) + using (var project = new VBProject(VBProject)) { - project.Dispose(); - return; - } + if (!IsInDesignMode() || VBProject.Protection == VB.vbext_ProjectProtection.vbext_pp_locked) + { + return; + } + + var projectId = project.ProjectId; - var projectId = project.ProjectId; + if (projectId == null) + { + return; + } - var handler = ProjectRenamed; - if (handler == null || projectId == null) - { - project.Dispose(); - return; + var handler = ProjectRenamed; + handler?.Invoke(this, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } - handler.Invoke(project, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } public event EventHandler ProjectActivated; diff --git a/RubberduckBaseProject.csproj b/RubberduckBaseProject.csproj index aae613ee2a..42f4f50329 100644 --- a/RubberduckBaseProject.csproj +++ b/RubberduckBaseProject.csproj @@ -45,7 +45,15 @@ AND '$(AssemblyName)' != 'RubberduckTestsCodeAnalysis'"> - + full false diff --git a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs index c6859cd983..4a9e2081c5 100644 --- a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs +++ b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs @@ -1129,7 +1129,7 @@ public void ExportProject_TestExecute_OKPressed_ExpectExecution() var uiDispatcher = new Mock(); var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); - vm.ExportAllCommand = new ExportAllCommand(null, mockFolderBrowserFactory.Object); + vm.ExportAllCommand = new ExportAllCommand(vbe.Object, mockFolderBrowserFactory.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource());