From 5539581e9c78d4d6c3a008778ccfcb28afd08539 Mon Sep 17 00:00:00 2001 From: bclothier Date: Sat, 3 Nov 2018 22:31:37 -0500 Subject: [PATCH 1/7] Additional leaks plugged --- .../Commands/AddMDIFormCommand.cs | 13 +++--- .../UI/Command/ExportAllCommand.cs | 33 ++++++++------- .../UI/Command/FindAllReferencesCommand.cs | 40 ++++++++++--------- .../CodePaneRefactorRenameCommand.cs | 2 +- .../UnitTesting/VBEInteraction.cs | 4 +- .../ComManagement/ComSafeBase.cs | 2 +- .../SafeComWrappers/VB/CodePane.cs | 25 +++++++----- .../SafeComWrappers/VB/CodePane.cs | 25 +++++++----- .../SafeComWrappers/VB/VBProject.cs | 18 +++++++-- 9 files changed, 97 insertions(+), 65 deletions(-) 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/Command/ExportAllCommand.cs b/Rubberduck.Core/UI/Command/ExportAllCommand.cs index bcdac6e99b..d53f181054 100644 --- a/Rubberduck.Core/UI/Command/ExportAllCommand.cs +++ b/Rubberduck.Core/UI/Command/ExportAllCommand.cs @@ -65,25 +65,28 @@ protected override void OnExecute(object parameter) var vbproject = parameter as IVBProject; - var project = projectNode?.Declaration.Project ?? vbproject ?? _vbe.ActiveVBProject; - - var desc = string.Format(RubberduckUI.ExportAllCommand_SaveAsDialog_Title, project.Name); - - // If .GetDirectoryName is passed an empty string for a RootFolder, - // it defaults to the Documents library (Win 7+) or equivalent. - var path = string.Empty; - if (!string.IsNullOrWhiteSpace(project.FileName)) + using (var activeProject = _vbe.ActiveVBProject) { - path = Path.GetDirectoryName(project.FileName); - } + var project = projectNode?.Declaration.Project ?? vbproject ?? activeProject; - using (var _folderBrowser = _factory.CreateFolderBrowser(desc, true, path)) - { - var result = _folderBrowser.ShowDialog(); + var desc = string.Format(RubberduckUI.ExportAllCommand_SaveAsDialog_Title, project.Name); - if (result == DialogResult.OK) + // If .GetDirectoryName is passed an empty string for a RootFolder, + // it defaults to the Documents library (Win 7+) or equivalent. + var path = string.Empty; + if (!string.IsNullOrWhiteSpace(project.FileName)) { - project.ExportSourceFiles(_folderBrowser.SelectedPath); + path = Path.GetDirectoryName(project.FileName); + } + + using (var _folderBrowser = _factory.CreateFolderBrowser(desc, true, path)) + { + var result = _folderBrowser.ShowDialog(); + + if (result == DialogResult.OK) + { + project.ExportSourceFiles(_folderBrowser.SelectedPath); + } } } } diff --git a/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs b/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs index db3cb0c440..bd9222e33b 100644 --- a/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs +++ b/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs @@ -224,32 +224,36 @@ 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; + } + + // Cannot use DeclarationType.UserForm, parser only assigns UserForms the ClassModule flag + (selectedType, selectedName) = selectedCount == 0 + ? (DeclarationType.ClassModule, component.Name) + : (DeclarationType.Control, selectedControls[0].Name); } - // 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; } - return null; } private Declaration FindFormDesignerTarget(QualifiedModuleName qualifiedModuleName) diff --git a/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs index 22272035d5..cd355aa920 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs @@ -56,7 +56,7 @@ protected override void OnExecute(object parameter) } else { - target = _state.FindSelectedDeclaration(Vbe.ActiveCodePane); + target = _state.FindSelectedDeclaration(activePane); } } diff --git a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs index 71a6a992c9..82c4714fbd 100644 --- a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs +++ b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs @@ -96,7 +96,9 @@ public void EnsureProjectReferencesUnitTesting(IVBProject project) if (!ReferenceWithPathExists(references, referencePath)) { - references.AddFromFile(referencePath); + // AddFromFile returns a new wrapped reference so we must + // ensure it is disposed properly. + using (references.AddFromFile(referencePath)) { } } } } diff --git a/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs b/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs index cbee17a160..f4cb5386a4 100644 --- a/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs +++ b/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs @@ -88,7 +88,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.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs index a5dbc8515f..8dd908f1cb 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 + { + System.Diagnostics.Debug.WriteLine( + "CodePane.ForceFocus() failed to get a handle on the MainWindow."); + } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs index 07e56869f4..1ac19c732e 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 + { + System.Diagnostics.Debug.WriteLine( + "CodePane.ForceFocus() failed to get a handle on the MainWindow."); + } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs index 05601067e7..5107f1fe97 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs @@ -100,7 +100,17 @@ 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 +184,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 { From b03a59d2d0facc87fda683096ecbaf13ffc93421 Mon Sep 17 00:00:00 2001 From: bclothier Date: Sun, 4 Nov 2018 10:38:05 -0600 Subject: [PATCH 2/7] Add IDisposable Analyzer and assess its usefulness. Fix some legitimate issues. Disable the analyzer due to numerous false positives. --- Rubberduck.API/VBA/Parser.cs | 13 +- .../QuickFixes/IgnoreOnceQuickFix.cs | 2 +- Rubberduck.Core/Common/ExportFormatter.cs | 395 +++++++++--------- .../Common/WinAPI/RegistryAccess.cs | 8 +- .../Common/WindowsOperatingSystem.cs | 3 +- .../Commands/CopyResultsCommand.cs | 26 +- .../UI/CodeExplorer/Commands/PrintCommand.cs | 24 +- .../CommandBars/AppCommandBarBase.cs | 1 + .../ParentMenus/ParentMenuItemBase.cs | 1 + .../Commands/AddTestModuleCommand.cs | 19 +- .../UI/UnitTesting/TestExplorerViewModel.cs | 20 +- Rubberduck.SmartIndenter/IndenterSettings.cs | 87 ++-- .../UnitTesting/VBEInteraction.cs | 57 +-- .../ComManagement/TypeLibs/TypeInfos.cs | 11 +- .../ComManagement/TypeLibs/TypeLibs.cs | 18 +- .../SafeComWrappers/VB/VBProjects.cs | 1 - .../Application/FallbackApp.cs | 8 + .../SafeComWrappers/VB/VBE.cs | 101 ++--- RubberduckBaseProject.csproj | 10 +- 19 files changed, 431 insertions(+), 374 deletions(-) diff --git a/Rubberduck.API/VBA/Parser.cs b/Rubberduck.API/VBA/Parser.cs index 727e638298..2b93d3ec8a 100644 --- a/Rubberduck.API/VBA/Parser.cs +++ b/Rubberduck.API/VBA/Parser.cs @@ -5,13 +5,11 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading; -using Rubberduck.Common; using Rubberduck.Parsing.ComReflection; using Rubberduck.Parsing.PreProcessing; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols.DeclarationLoaders; using Rubberduck.Parsing.VBA; -using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.UIContext; using Rubberduck.Parsing.VBA.ComReferenceLoading; using Rubberduck.Parsing.VBA.DeclarationCaching; @@ -69,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; @@ -235,6 +233,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 65ae67fd15..6b68ab5477 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs @@ -32,7 +32,7 @@ public override void Fix(IInspectionResult result) int annotationLine; string codeLine; - 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/WinAPI/RegistryAccess.cs b/Rubberduck.Core/Common/WinAPI/RegistryAccess.cs index 6e048ad08d..f8cd272104 100644 --- a/Rubberduck.Core/Common/WinAPI/RegistryAccess.cs +++ b/Rubberduck.Core/Common/WinAPI/RegistryAccess.cs @@ -18,9 +18,11 @@ internal static RegistryKey GetDeviceKey(string device) internal static string GetClassType(string classGuid) { - var classGuidKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\" + classGuid); - - return classGuidKey != null ? (string)classGuidKey.GetValue("Class") : string.Empty; + using (var classGuidKey = + Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\" + classGuid)) + { + return classGuidKey != null ? (string) classGuidKey.GetValue("Class") : string.Empty; + } } } } 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/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/MenuItems/CommandBars/AppCommandBarBase.cs b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs index 63cd0e9160..8eaf23b453 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs @@ -87,6 +87,7 @@ public virtual void Initialize() try { + Item?.Dispose(); Item = Parent.Add(_name, _position); Item.IsVisible = true; } diff --git a/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs b/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs index 8b6e4b75a7..bf4591a11c 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs @@ -73,6 +73,7 @@ public void Initialize() return; } + Item?.Dispose(); Item = Parent.AddPopup(_beforeIndex); Item.Tag = _key; diff --git a/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs b/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs index 67d2bb3ff8..2e92fce87d 100644 --- a/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs +++ b/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs @@ -125,13 +125,12 @@ private string DeclarationFormatFor(string declarationFormat, string type, IUnit private IVBProject GetProject() { - var activeProject = _vbe.ActiveVBProject; - if (!activeProject.IsWrappingNullReference) - { - return activeProject; + using (var activeProject = _vbe.ActiveVBProject) + { if (!activeProject.IsWrappingNullReference) + { + return activeProject; + } } - - activeProject.Dispose(); using (var projects = _vbe.VBProjects) { @@ -158,9 +157,11 @@ 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())) + using (var activeProject = GetProject()) { + var project = parameter as IVBProject ?? + (parameterIsModuleDeclaration ? ((Declaration) parameter).Project : activeProject); + if (project == null || project.IsWrappingNullReference) { return; @@ -197,7 +198,7 @@ protected override void OnExecute(object parameter) if (parameterIsModuleDeclaration) { var moduleCodeBuilder = new StringBuilder(); - var declarationsToStub = GetDeclarationsToStub((Declaration) parameter); + var declarationsToStub = GetDeclarationsToStub((Declaration)parameter); foreach (var declaration in declarationsToStub) { 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.SmartIndenter/IndenterSettings.cs b/Rubberduck.SmartIndenter/IndenterSettings.cs index af8f63c60e..2e4236d1f3 100644 --- a/Rubberduck.SmartIndenter/IndenterSettings.cs +++ b/Rubberduck.SmartIndenter/IndenterSettings.cs @@ -134,11 +134,13 @@ public IndenterSettings(bool skipRegistry) { try { - var reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\6.0\Common", false) ?? - Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\7.0\Common", false); - if (reg != null) + using (var reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\6.0\Common", false) ?? + Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\7.0\Common", false)) { - tabWidth = Convert.ToInt32(reg.GetValue("TabWidth") ?? tabWidth); + if (reg != null) + { + tabWidth = Convert.ToInt32(reg.GetValue("TabWidth") ?? tabWidth); + } } } // ReSharper disable once EmptyGeneralCatchClause @@ -219,45 +221,52 @@ public void LoadLegacyFromRegistry() { try { - var reg = Registry.CurrentUser.OpenSubKey(LegacySettingsSubKey, false); - if (reg == null) return; - IndentEntireProcedureBody = GetSmartIndenterBoolean(reg, "IndentProc", IndentEntireProcedureBody); - IndentFirstCommentBlock = GetSmartIndenterBoolean(reg, "IndentFirst", IndentFirstCommentBlock); - IndentFirstDeclarationBlock = GetSmartIndenterBoolean(reg, "IndentDim", IndentFirstDeclarationBlock); - AlignCommentsWithCode = GetSmartIndenterBoolean(reg, "IndentCmt", AlignCommentsWithCode); - AlignContinuations = GetSmartIndenterBoolean(reg, "AlignContinued", AlignContinuations); - IgnoreOperatorsInContinuations = GetSmartIndenterBoolean(reg, "AlignIgnoreOps", IgnoreOperatorsInContinuations); - IndentCase = GetSmartIndenterBoolean(reg, "IndentCase", IndentCase); - ForceDebugStatementsInColumn1 = GetSmartIndenterBoolean(reg, "DebugCol1", ForceDebugStatementsInColumn1); - ForceDebugPrintInColumn1 = ForceDebugStatementsInColumn1; - ForceDebugAssertInColumn1 = ForceDebugStatementsInColumn1; - ForceStopInColumn1 = ForceDebugStatementsInColumn1; - ForceCompilerDirectivesInColumn1 = GetSmartIndenterBoolean(reg, "CompilerCol1", ForceCompilerDirectivesInColumn1); - IndentCompilerDirectives = GetSmartIndenterBoolean(reg, "IndentCompiler", IndentCompilerDirectives); - AlignDims = GetSmartIndenterBoolean(reg, "AlignDim", AlignDims); - AlignDimColumn = GetSmartIndenterNumeric(reg, "AlignDimCol", AlignDimColumn, MaximumAlignDimColumn); - - var eolSytle = reg.GetValue("EOLComments") as string; - if (!string.IsNullOrEmpty(eolSytle)) + using (var reg = Registry.CurrentUser.OpenSubKey(LegacySettingsSubKey, false)) { - switch (eolSytle) + if (reg == null) return; + IndentEntireProcedureBody = GetSmartIndenterBoolean(reg, "IndentProc", IndentEntireProcedureBody); + IndentFirstCommentBlock = GetSmartIndenterBoolean(reg, "IndentFirst", IndentFirstCommentBlock); + IndentFirstDeclarationBlock = + GetSmartIndenterBoolean(reg, "IndentDim", IndentFirstDeclarationBlock); + AlignCommentsWithCode = GetSmartIndenterBoolean(reg, "IndentCmt", AlignCommentsWithCode); + AlignContinuations = GetSmartIndenterBoolean(reg, "AlignContinued", AlignContinuations); + IgnoreOperatorsInContinuations = + GetSmartIndenterBoolean(reg, "AlignIgnoreOps", IgnoreOperatorsInContinuations); + IndentCase = GetSmartIndenterBoolean(reg, "IndentCase", IndentCase); + ForceDebugStatementsInColumn1 = + GetSmartIndenterBoolean(reg, "DebugCol1", ForceDebugStatementsInColumn1); + ForceDebugPrintInColumn1 = ForceDebugStatementsInColumn1; + ForceDebugAssertInColumn1 = ForceDebugStatementsInColumn1; + ForceStopInColumn1 = ForceDebugStatementsInColumn1; + ForceCompilerDirectivesInColumn1 = + GetSmartIndenterBoolean(reg, "CompilerCol1", ForceCompilerDirectivesInColumn1); + IndentCompilerDirectives = GetSmartIndenterBoolean(reg, "IndentCompiler", IndentCompilerDirectives); + AlignDims = GetSmartIndenterBoolean(reg, "AlignDim", AlignDims); + AlignDimColumn = GetSmartIndenterNumeric(reg, "AlignDimCol", AlignDimColumn, MaximumAlignDimColumn); + + var eolSytle = reg.GetValue("EOLComments") as string; + if (!string.IsNullOrEmpty(eolSytle)) { - case "Absolute": - EndOfLineCommentStyle = EndOfLineCommentStyle.Absolute; - break; - case "SameGap": - EndOfLineCommentStyle = EndOfLineCommentStyle.SameGap; - break; - case "StandardGap": - EndOfLineCommentStyle = EndOfLineCommentStyle.StandardGap; - break; - case "AlignInCol": - EndOfLineCommentStyle = EndOfLineCommentStyle.AlignInColumn; - break; + switch (eolSytle) + { + case "Absolute": + EndOfLineCommentStyle = EndOfLineCommentStyle.Absolute; + break; + case "SameGap": + EndOfLineCommentStyle = EndOfLineCommentStyle.SameGap; + break; + case "StandardGap": + EndOfLineCommentStyle = EndOfLineCommentStyle.StandardGap; + break; + case "AlignInCol": + EndOfLineCommentStyle = EndOfLineCommentStyle.AlignInColumn; + break; + } } + + EndOfLineCommentColumnSpaceAlignment = GetSmartIndenterNumeric(reg, "EOLAlignCol", + EndOfLineCommentColumnSpaceAlignment, MaximumEndOfLineCommentColumnSpaceAlignment); } - EndOfLineCommentColumnSpaceAlignment = GetSmartIndenterNumeric(reg, "EOLAlignCol", - EndOfLineCommentColumnSpaceAlignment, MaximumEndOfLineCommentColumnSpaceAlignment); } // ReSharper disable once EmptyGeneralCatchClause catch { } diff --git a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs index 82c4714fbd..82e94f884b 100644 --- a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs +++ b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs @@ -67,38 +67,45 @@ 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 referencePath = pathKey?.GetValue(string.Empty, string.Empty) as string; - string name = null; - - if (!string.IsNullOrWhiteSpace(referencePath)) + using (var pathKey = Registry.ClassesRoot.OpenSubKey( + $@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}\0\{libFolder}")) { - var tlbKey = - Registry.ClassesRoot.OpenSubKey($@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}"); + var referencePath = pathKey?.GetValue(string.Empty, string.Empty) as string; + string name = null; - name = tlbKey?.GetValue(string.Empty, string.Empty) as string; - } - - 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)) + { + using (var tlbKey = + Registry.ClassesRoot.OpenSubKey( + $@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}")) + { + name = tlbKey?.GetValue(string.Empty, string.Empty) as string; + } + } - 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) { - // AddFromFile returns a new wrapped reference so we must - // ensure it is disposed properly. - using (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)) + { + } + } } } } 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/VBProjects.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs index 1edc45584b..38819a33dd 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs @@ -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 02e1f514ad..cec9e6d485 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs @@ -52,8 +52,16 @@ public TimeSpan TimedMethodCall(dynamic declaration) public string ApplicationName => "(unknown)"; + private bool _disposed; public void Dispose() { + if (_disposed) + { + return; + } + + _disposed = true; + _runButton.Dispose(); } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs index 42cbe56122..a61263c132 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs @@ -200,66 +200,67 @@ 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(); - break; - case "Microsoft Access": - result = new AccessApp(); - break; - case "Microsoft Word": - result = new WordApp(); - break; - case "Microsoft PowerPoint": - result = new PowerPointApp(this); - break; - case "Microsoft Outlook": - result = new OutlookApp(); - break; - case "Microsoft Project": - result = new ProjectApp(); - break; - case "Microsoft Publisher": - result = new PublisherApp(); - break; - case "Microsoft Visio": - result = new VisioApp(); - break; - case "AutoCAD": - result = new AutoCADApp(); - break; - case "CorelDRAW": - result = new CorelDRAWApp(); - break; - case "SolidWorks": - result = new SolidWorksApp(this); - break; - default: - result = null; - break; + result = null; + } + else + { + switch (hostAppControl.Caption) + { + case "Microsoft Excel": + result = new ExcelApp(); + break; + case "Microsoft Access": + result = new AccessApp(); + break; + case "Microsoft Word": + result = new WordApp(); + break; + case "Microsoft PowerPoint": + result = new PowerPointApp(this); + break; + case "Microsoft Outlook": + result = new OutlookApp(); + break; + case "Microsoft Project": + result = new ProjectApp(); + break; + case "Microsoft Publisher": + result = new PublisherApp(); + break; + case "Microsoft Visio": + result = new VisioApp(); + break; + case "AutoCAD": + result = new AutoCADApp(); + break; + case "CorelDRAW": + result = new CorelDRAWApp(); + break; + case "SolidWorks": + result = new SolidWorksApp(this); + break; + default: + result = null; + break; + } } - } - _host = result; - return result; + _host = result; + return result; + } } } diff --git a/RubberduckBaseProject.csproj b/RubberduckBaseProject.csproj index 6d8f658ad9..63b0e01ec2 100644 --- a/RubberduckBaseProject.csproj +++ b/RubberduckBaseProject.csproj @@ -45,7 +45,15 @@ AND '$(AssemblyName)' != 'RubberduckTestsCodeAnalysis'"> - + full false From 14665a34a5c5358952a895a77a1f9fe6c9dceee0 Mon Sep 17 00:00:00 2001 From: bclothier Date: Sun, 4 Nov 2018 11:46:59 -0600 Subject: [PATCH 3/7] Add missing Dispose for conditional returns. --- Rubberduck.VBEEditor/Events/VbeEvents.cs | 1 + .../SafeComWrappers/VB/VBProjects.cs | 28 ++++++++++--------- .../SafeComWrappers/VB/VBProjects.cs | 28 ++++++++++--------- 3 files changed, 31 insertions(+), 26 deletions(-) diff --git a/Rubberduck.VBEEditor/Events/VbeEvents.cs b/Rubberduck.VBEEditor/Events/VbeEvents.cs index 213cae5f5a..a2228cc266 100644 --- a/Rubberduck.VBEEditor/Events/VbeEvents.cs +++ b/Rubberduck.VBEEditor/Events/VbeEvents.cs @@ -73,6 +73,7 @@ private void RegisterComponents(string projectId, string projectName) if (item.ProjectId == projectId && item.Name == projectName) { project = item; + item.Dispose(); break; } diff --git a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs index 38819a33dd..9abfb6094e 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs @@ -92,23 +92,25 @@ 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()) + { + project.Dispose(); + return; + } - var projectId = project.ProjectId; + var projectId = project.ProjectId; - var handler = ProjectRenamed; - if (handler == null || projectId == null) - { - project.Dispose(); - return; + var handler = ProjectRenamed; + if (handler == null || projectId == null) + { + project.Dispose(); + return; + } + + 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/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs index 1f066722c2..389e32fa79 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs @@ -96,23 +96,25 @@ 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) + { + project.Dispose(); + return; + } - var projectId = project.ProjectId; + var projectId = project.ProjectId; - var handler = ProjectRenamed; - if (handler == null || projectId == null) - { - project.Dispose(); - return; + var handler = ProjectRenamed; + if (handler == null || projectId == null) + { + project.Dispose(); + return; + } + + handler.Invoke(this, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } - handler.Invoke(project, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } public event EventHandler ProjectActivated; From 9bfbca0c70aeb0bc928930cf931d3713b13abb59 Mon Sep 17 00:00:00 2001 From: bclothier Date: Sun, 4 Nov 2018 14:38:30 -0600 Subject: [PATCH 4/7] Fix a failing unit test due to not passing in the mocked vbe object. --- RubberduckTests/CodeExplorer/CodeExplorerTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs index 7e2211e59f..dba57ebd8d 100644 --- a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs +++ b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs @@ -1135,7 +1135,7 @@ public void ExportProject_TestExecute_OKPressed_ExpectExecution() var uiDispatcher = new Mock(); var vm = new CodeExplorerViewModel(new FolderHelper(state), 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()); From 84503b7d60f2514f1c5567a54f338c1d8ab52e14 Mon Sep 17 00:00:00 2001 From: bclothier Date: Mon, 5 Nov 2018 06:22:25 -0600 Subject: [PATCH 5/7] Address PR comments Revert changes to RegistryAccess and IndenterSettings -- registry work requires more thought than simply wrapping a new using block. --- .../Common/WinAPI/RegistryAccess.cs | 8 +- .../UI/Command/ExportAllCommand.cs | 52 +++--- .../UI/Command/FindAllReferencesCommand.cs | 19 ++- .../CommandBars/AppCommandBarBase.cs | 25 ++- .../ParentMenus/ParentMenuItemBase.cs | 25 ++- .../Commands/AddTestModuleCommand.cs | 160 ++++++++++-------- Rubberduck.SmartIndenter/IndenterSettings.cs | 87 +++++----- .../UnitTesting/VBEInteraction.cs | 23 ++- .../SafeComWrappers/VB/VBProject.cs | 14 +- .../SafeComWrappers/VB/VBProjects.cs | 2 - .../SafeComWrappers/VB/VBProject.cs | 8 +- .../SafeComWrappers/VB/VBProjects.cs | 2 - 12 files changed, 250 insertions(+), 175 deletions(-) diff --git a/Rubberduck.Core/Common/WinAPI/RegistryAccess.cs b/Rubberduck.Core/Common/WinAPI/RegistryAccess.cs index f8cd272104..6e048ad08d 100644 --- a/Rubberduck.Core/Common/WinAPI/RegistryAccess.cs +++ b/Rubberduck.Core/Common/WinAPI/RegistryAccess.cs @@ -18,11 +18,9 @@ internal static RegistryKey GetDeviceKey(string device) internal static string GetClassType(string classGuid) { - using (var classGuidKey = - Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\" + classGuid)) - { - return classGuidKey != null ? (string) classGuidKey.GetValue("Class") : string.Empty; - } + var classGuidKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\" + classGuid); + + return classGuidKey != null ? (string)classGuidKey.GetValue("Class") : string.Empty; } } } diff --git a/Rubberduck.Core/UI/Command/ExportAllCommand.cs b/Rubberduck.Core/UI/Command/ExportAllCommand.cs index d53f181054..97d2c70fe5 100644 --- a/Rubberduck.Core/UI/Command/ExportAllCommand.cs +++ b/Rubberduck.Core/UI/Command/ExportAllCommand.cs @@ -61,32 +61,44 @@ private bool Evaluate(IVBProject project) protected override void OnExecute(object parameter) { - var projectNode = parameter as CodeExplorerProjectViewModel; + 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 vbproject = parameter as IVBProject; + private void Export(IVBProject project) + { + var desc = string.Format(RubberduckUI.ExportAllCommand_SaveAsDialog_Title, project.Name); - using (var activeProject = _vbe.ActiveVBProject) + // If .GetDirectoryName is passed an empty string for a RootFolder, + // it defaults to the Documents library (Win 7+) or equivalent. + var path = string.Empty; + if (!string.IsNullOrWhiteSpace(project.FileName)) { - var project = projectNode?.Declaration.Project ?? vbproject ?? activeProject; - - var desc = string.Format(RubberduckUI.ExportAllCommand_SaveAsDialog_Title, project.Name); + path = Path.GetDirectoryName(project.FileName); + } - // If .GetDirectoryName is passed an empty string for a RootFolder, - // it defaults to the Documents library (Win 7+) or equivalent. - var path = string.Empty; - if (!string.IsNullOrWhiteSpace(project.FileName)) - { - path = Path.GetDirectoryName(project.FileName); - } + using (var _folderBrowser = _factory.CreateFolderBrowser(desc, true, path)) + { + var result = _folderBrowser.ShowDialog(); - using (var _folderBrowser = _factory.CreateFolderBrowser(desc, true, path)) + if (result == DialogResult.OK) { - var result = _folderBrowser.ShowDialog(); - - if (result == DialogResult.OK) - { - project.ExportSourceFiles(_folderBrowser.SelectedPath); - } + project.ExportSourceFiles(_folderBrowser.SelectedPath); } } } diff --git a/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs b/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs index bd9222e33b..1d5036463a 100644 --- a/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs +++ b/Rubberduck.Core/UI/Command/FindAllReferencesCommand.cs @@ -239,10 +239,7 @@ private Declaration FindFormDesignerTarget(QualifiedModuleName? qualifiedModuleN return null; } - // Cannot use DeclarationType.UserForm, parser only assigns UserForms the ClassModule flag - (selectedType, selectedName) = selectedCount == 0 - ? (DeclarationType.ClassModule, component.Name) - : (DeclarationType.Control, selectedControls[0].Name); + (selectedType, selectedName) = GetSelectedName(component, selectedControls, selectedCount); } return _state.DeclarationFinder @@ -256,6 +253,20 @@ private Declaration FindFormDesignerTarget(QualifiedModuleName? qualifiedModuleN } } + 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); + } + } + private Declaration FindFormDesignerTarget(QualifiedModuleName qualifiedModuleName) { var projectId = qualifiedModuleName.ProjectId; diff --git a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs index 8eaf23b453..4b47c4219e 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs @@ -87,7 +87,6 @@ public virtual void Initialize() try { - Item?.Dispose(); Item = Parent.Add(_name, _position); Item.IsVisible = true; } @@ -170,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() { @@ -184,7 +202,6 @@ public void RemoveCommandBar() Item.Delete(); Item.Dispose(); 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 bf4591a11c..71df1c8b6f 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; @@ -73,7 +92,6 @@ public void Initialize() return; } - Item?.Dispose(); Item = Parent.AddPopup(_beforeIndex); Item.Tag = _key; @@ -92,7 +110,6 @@ public void RemoveMenu() Logger.Debug($"Removing menu {_key}."); RemoveChildren(); Item?.Delete(); - Item?.Dispose(); Item = null; } diff --git a/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs b/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs index 2e92fce87d..7fbdd570ab 100644 --- a/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs +++ b/Rubberduck.Core/UI/UnitTesting/Commands/AddTestModuleCommand.cs @@ -126,7 +126,8 @@ private string DeclarationFormatFor(string declarationFormat, string type, IUnit private IVBProject GetProject() { using (var activeProject = _vbe.ActiveVBProject) - { if (!activeProject.IsWrappingNullReference) + { + if (!activeProject.IsWrappingNullReference) { return activeProject; } @@ -157,102 +158,115 @@ protected override void OnExecute(object parameter) { var parameterIsModuleDeclaration = parameter is ProceduralModuleDeclaration || parameter is ClassModuleDeclaration; - using (var activeProject = GetProject()) + switch(parameter) { - var project = parameter as IVBProject ?? - (parameterIsModuleDeclaration ? ((Declaration) parameter).Project : activeProject); - - 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; - try + if (settings.BindingMode == BindingMode.EarlyBinding) + { + // FIXME: Push the actual adding of TestModules into UnitTesting, which sidesteps VBEInteraction being inaccessble here + _interaction.EnsureProjectReferencesUnitTesting(project); + } + + 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.SmartIndenter/IndenterSettings.cs b/Rubberduck.SmartIndenter/IndenterSettings.cs index 2e4236d1f3..af8f63c60e 100644 --- a/Rubberduck.SmartIndenter/IndenterSettings.cs +++ b/Rubberduck.SmartIndenter/IndenterSettings.cs @@ -134,13 +134,11 @@ public IndenterSettings(bool skipRegistry) { try { - using (var reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\6.0\Common", false) ?? - Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\7.0\Common", false)) + var reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\6.0\Common", false) ?? + Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VBA\7.0\Common", false); + if (reg != null) { - if (reg != null) - { - tabWidth = Convert.ToInt32(reg.GetValue("TabWidth") ?? tabWidth); - } + tabWidth = Convert.ToInt32(reg.GetValue("TabWidth") ?? tabWidth); } } // ReSharper disable once EmptyGeneralCatchClause @@ -221,52 +219,45 @@ public void LoadLegacyFromRegistry() { try { - using (var reg = Registry.CurrentUser.OpenSubKey(LegacySettingsSubKey, false)) - { - if (reg == null) return; - IndentEntireProcedureBody = GetSmartIndenterBoolean(reg, "IndentProc", IndentEntireProcedureBody); - IndentFirstCommentBlock = GetSmartIndenterBoolean(reg, "IndentFirst", IndentFirstCommentBlock); - IndentFirstDeclarationBlock = - GetSmartIndenterBoolean(reg, "IndentDim", IndentFirstDeclarationBlock); - AlignCommentsWithCode = GetSmartIndenterBoolean(reg, "IndentCmt", AlignCommentsWithCode); - AlignContinuations = GetSmartIndenterBoolean(reg, "AlignContinued", AlignContinuations); - IgnoreOperatorsInContinuations = - GetSmartIndenterBoolean(reg, "AlignIgnoreOps", IgnoreOperatorsInContinuations); - IndentCase = GetSmartIndenterBoolean(reg, "IndentCase", IndentCase); - ForceDebugStatementsInColumn1 = - GetSmartIndenterBoolean(reg, "DebugCol1", ForceDebugStatementsInColumn1); - ForceDebugPrintInColumn1 = ForceDebugStatementsInColumn1; - ForceDebugAssertInColumn1 = ForceDebugStatementsInColumn1; - ForceStopInColumn1 = ForceDebugStatementsInColumn1; - ForceCompilerDirectivesInColumn1 = - GetSmartIndenterBoolean(reg, "CompilerCol1", ForceCompilerDirectivesInColumn1); - IndentCompilerDirectives = GetSmartIndenterBoolean(reg, "IndentCompiler", IndentCompilerDirectives); - AlignDims = GetSmartIndenterBoolean(reg, "AlignDim", AlignDims); - AlignDimColumn = GetSmartIndenterNumeric(reg, "AlignDimCol", AlignDimColumn, MaximumAlignDimColumn); + var reg = Registry.CurrentUser.OpenSubKey(LegacySettingsSubKey, false); + if (reg == null) return; + IndentEntireProcedureBody = GetSmartIndenterBoolean(reg, "IndentProc", IndentEntireProcedureBody); + IndentFirstCommentBlock = GetSmartIndenterBoolean(reg, "IndentFirst", IndentFirstCommentBlock); + IndentFirstDeclarationBlock = GetSmartIndenterBoolean(reg, "IndentDim", IndentFirstDeclarationBlock); + AlignCommentsWithCode = GetSmartIndenterBoolean(reg, "IndentCmt", AlignCommentsWithCode); + AlignContinuations = GetSmartIndenterBoolean(reg, "AlignContinued", AlignContinuations); + IgnoreOperatorsInContinuations = GetSmartIndenterBoolean(reg, "AlignIgnoreOps", IgnoreOperatorsInContinuations); + IndentCase = GetSmartIndenterBoolean(reg, "IndentCase", IndentCase); + ForceDebugStatementsInColumn1 = GetSmartIndenterBoolean(reg, "DebugCol1", ForceDebugStatementsInColumn1); + ForceDebugPrintInColumn1 = ForceDebugStatementsInColumn1; + ForceDebugAssertInColumn1 = ForceDebugStatementsInColumn1; + ForceStopInColumn1 = ForceDebugStatementsInColumn1; + ForceCompilerDirectivesInColumn1 = GetSmartIndenterBoolean(reg, "CompilerCol1", ForceCompilerDirectivesInColumn1); + IndentCompilerDirectives = GetSmartIndenterBoolean(reg, "IndentCompiler", IndentCompilerDirectives); + AlignDims = GetSmartIndenterBoolean(reg, "AlignDim", AlignDims); + AlignDimColumn = GetSmartIndenterNumeric(reg, "AlignDimCol", AlignDimColumn, MaximumAlignDimColumn); - var eolSytle = reg.GetValue("EOLComments") as string; - if (!string.IsNullOrEmpty(eolSytle)) + var eolSytle = reg.GetValue("EOLComments") as string; + if (!string.IsNullOrEmpty(eolSytle)) + { + switch (eolSytle) { - switch (eolSytle) - { - case "Absolute": - EndOfLineCommentStyle = EndOfLineCommentStyle.Absolute; - break; - case "SameGap": - EndOfLineCommentStyle = EndOfLineCommentStyle.SameGap; - break; - case "StandardGap": - EndOfLineCommentStyle = EndOfLineCommentStyle.StandardGap; - break; - case "AlignInCol": - EndOfLineCommentStyle = EndOfLineCommentStyle.AlignInColumn; - break; - } + case "Absolute": + EndOfLineCommentStyle = EndOfLineCommentStyle.Absolute; + break; + case "SameGap": + EndOfLineCommentStyle = EndOfLineCommentStyle.SameGap; + break; + case "StandardGap": + EndOfLineCommentStyle = EndOfLineCommentStyle.StandardGap; + break; + case "AlignInCol": + EndOfLineCommentStyle = EndOfLineCommentStyle.AlignInColumn; + break; } - - EndOfLineCommentColumnSpaceAlignment = GetSmartIndenterNumeric(reg, "EOLAlignCol", - EndOfLineCommentColumnSpaceAlignment, MaximumEndOfLineCommentColumnSpaceAlignment); } + EndOfLineCommentColumnSpaceAlignment = GetSmartIndenterNumeric(reg, "EOLAlignCol", + EndOfLineCommentColumnSpaceAlignment, MaximumEndOfLineCommentColumnSpaceAlignment); } // ReSharper disable once EmptyGeneralCatchClause catch { } diff --git a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs index 82e94f884b..ddc0e1c9f4 100644 --- a/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs +++ b/Rubberduck.UnitTesting/UnitTesting/VBEInteraction.cs @@ -67,19 +67,24 @@ public void EnsureProjectReferencesUnitTesting(IVBProject project) if (project == null || project.IsWrappingNullReference) { return; } var libFolder = IntPtr.Size == 8 ? "win64" : "win32"; const string libGuid = RubberduckGuid.RubberduckTypeLibGuid; - using (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}"); + + if (pathKey != null) { - var referencePath = pathKey?.GetValue(string.Empty, string.Empty) as string; + var referencePath = pathKey.GetValue(string.Empty, string.Empty) as string; string name = null; if (!string.IsNullOrWhiteSpace(referencePath)) { - using (var tlbKey = + var tlbKey = Registry.ClassesRoot.OpenSubKey( - $@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}")) + $@"TypeLib\{{{libGuid}}}\{_rubberduckVersion.Major}.{_rubberduckVersion.Minor}"); + + if(tlbKey != null) { - name = tlbKey?.GetValue(string.Empty, string.Empty) as string; + name = tlbKey.GetValue(string.Empty, string.Empty) as string; + tlbKey.Dispose(); } } @@ -102,11 +107,11 @@ public void EnsureProjectReferencesUnitTesting(IVBProject project) { // AddFromFile returns a new wrapped reference so we must // ensure it is disposed properly. - using (references.AddFromFile(referencePath)) - { - } + using (references.AddFromFile(referencePath)) { } } } + + pathKey.Dispose(); } } 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 9abfb6094e..aa66090d0d 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs @@ -96,7 +96,6 @@ void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), I { if (!IsInDesignMode()) { - project.Dispose(); return; } @@ -105,7 +104,6 @@ void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), I var handler = ProjectRenamed; if (handler == null || projectId == null) { - project.Dispose(); return; } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs index 5107f1fe97..2b2368245a 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProject.cs @@ -103,10 +103,12 @@ public IReadOnlyList ComponentNames() var names = new List(); using (var components = VBComponents) { - foreach(var component in components) - using (component) + foreach (var component in components) { - names.Add(component.Name); + using (component) + { + names.Add(component.Name); + } } return names.ToArray(); diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs index 389e32fa79..ed554448ee 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs @@ -100,7 +100,6 @@ void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), I { if (!IsInDesignMode() || VBProject.Protection == VB.vbext_ProjectProtection.vbext_pp_locked) { - project.Dispose(); return; } @@ -109,7 +108,6 @@ void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), I var handler = ProjectRenamed; if (handler == null || projectId == null) { - project.Dispose(); return; } From 1d1b55ac0a31f407e58e6f5c56a1a82738515b02 Mon Sep 17 00:00:00 2001 From: bclothier Date: Mon, 5 Nov 2018 23:08:19 -0600 Subject: [PATCH 6/7] Remove unneeded Dispose --- .../UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs index 4b47c4219e..8c1c76f8bb 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs @@ -200,7 +200,6 @@ public void RemoveCommandBar() Logger.Debug("Removing commandbar."); RemoveChildren(); Item.Delete(); - Item.Dispose(); Item = null; Parent = null; } From 869f7834e8ddfc389f2c3eed99a2b5f8a1b88751 Mon Sep 17 00:00:00 2001 From: bclothier Date: Mon, 12 Nov 2018 22:21:40 -0600 Subject: [PATCH 7/7] Address PR comments --- .../CommandBars/AppCommandBarBase.cs | 2 + .../ParentMenus/ParentMenuItemBase.cs | 2 + .../Rubberduck.Resources.csproj | 144 ++++++++++++++++++ Rubberduck.VBEEditor/Events/VbeEvents.cs | 1 - .../SafeComWrappers/VB/CodePane.cs | 2 +- .../SafeComWrappers/VB/VBProjects.cs | 6 +- .../SafeComWrappers/VB/CodePane.cs | 2 +- .../SafeComWrappers/VB/VBProjects.cs | 6 +- 8 files changed, 156 insertions(+), 9 deletions(-) diff --git a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs index 8c1c76f8bb..ff67c2ff84 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/CommandBars/AppCommandBarBase.cs @@ -200,6 +200,8 @@ public void RemoveCommandBar() Logger.Debug("Removing commandbar."); RemoveChildren(); Item.Delete(); + + // Setting them to null will automatically dispose those Item = null; Parent = null; } diff --git a/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs b/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs index 71df1c8b6f..713a256f24 100644 --- a/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs +++ b/Rubberduck.Core/UI/Command/MenuItems/ParentMenus/ParentMenuItemBase.cs @@ -110,6 +110,8 @@ public void RemoveMenu() Logger.Debug($"Removing menu {_key}."); RemoveChildren(); Item?.Delete(); + + //This will also dispose the Item as well Item = null; } diff --git a/Rubberduck.Resources/Rubberduck.Resources.csproj b/Rubberduck.Resources/Rubberduck.Resources.csproj index bfee94b500..c13d96be02 100644 --- a/Rubberduck.Resources/Rubberduck.Resources.csproj +++ b/Rubberduck.Resources/Rubberduck.Resources.csproj @@ -30,26 +30,170 @@ + + True + True + AboutUI.resx + + + True + True + CodeExplorerUI.resx + + + True + True + CommandBarIcons.resx + + + True + True + InspectionInfo.resx + + + True + True + InspectionNames.resx + + + True + True + InspectionResults.resx + + + True + True + InspectionsUI.resx + + + True + True + QuickFixes.resx + + + True + True + RubberduckMenus.resx + + + True + True + RegexAssistantUI.resx + True True RubberduckUI.resx + + True + True + AutoCompletesPage.resx + True True SettingsUI.resx + + True + True + ToDoExplorerPage.resx + + + True + True + UnitTestingPage.resx + + + True + True + ToDoExplorerUI.resx + + + True + True + AssertMessages.resx + + + True + True + TestExplorer.resx + + + PublicResXFileCodeGenerator + AboutUI.Designer.cs + + + PublicResXFileCodeGenerator + CodeExplorerUI.Designer.cs + + + PublicResXFileCodeGenerator + CommandBarIcons.Designer.cs + + + PublicResXFileCodeGenerator + InspectionInfo.Designer.cs + + + PublicResXFileCodeGenerator + InspectionNames.Designer.cs + + + PublicResXFileCodeGenerator + InspectionResults.Designer.cs + + + PublicResXFileCodeGenerator + InspectionsUI.Designer.cs + + + PublicResXFileCodeGenerator + QuickFixes.Designer.cs + + + PublicResXFileCodeGenerator + RubberduckMenus.Designer.cs + + + PublicResXFileCodeGenerator + RegexAssistantUI.Designer.cs + PublicResXFileCodeGenerator RubberduckUI.Designer.cs + + PublicResXFileCodeGenerator + AutoCompletesPage.Designer.cs + PublicResXFileCodeGenerator SettingsUI.Designer.cs + + PublicResXFileCodeGenerator + ToDoExplorerPage.Designer.cs + + + PublicResXFileCodeGenerator + UnitTestingPage.Designer.cs + + + PublicResXFileCodeGenerator + ToDoExplorerUI.Designer.cs + + + PublicResXFileCodeGenerator + AssertMessages.Designer.cs + + + PublicResXFileCodeGenerator + TestExplorer.Designer.cs + \ No newline at end of file diff --git a/Rubberduck.VBEEditor/Events/VbeEvents.cs b/Rubberduck.VBEEditor/Events/VbeEvents.cs index a2228cc266..213cae5f5a 100644 --- a/Rubberduck.VBEEditor/Events/VbeEvents.cs +++ b/Rubberduck.VBEEditor/Events/VbeEvents.cs @@ -73,7 +73,6 @@ private void RegisterComponents(string projectId, string projectName) if (item.ProjectId == projectId && item.Name == projectName) { project = item; - item.Dispose(); break; } diff --git a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs index 8dd908f1cb..387f58e1ea 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/CodePane.cs @@ -115,7 +115,7 @@ private void ForceFocus() } else { - System.Diagnostics.Debug.WriteLine( + _logger.Debug( "CodePane.ForceFocus() failed to get a handle on the MainWindow."); } } diff --git a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs index aa66090d0d..3a4355e4d5 100644 --- a/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VB6/SafeComWrappers/VB/VBProjects.cs @@ -101,13 +101,13 @@ void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), I var projectId = project.ProjectId; - var handler = ProjectRenamed; - if (handler == null || projectId == null) + if (projectId == null) { return; } - handler.Invoke(this, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); + var handler = ProjectRenamed; + handler?.Invoke(this, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs index 1ac19c732e..99498a89a7 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/CodePane.cs @@ -115,7 +115,7 @@ private void ForceFocus() } else { - System.Diagnostics.Debug.WriteLine( + _logger.Debug( "CodePane.ForceFocus() failed to get a handle on the MainWindow."); } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs index ed554448ee..8fd7c9ada1 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBProjects.cs @@ -105,13 +105,13 @@ void VB._dispVBProjectsEvents.ItemRenamed([MarshalAs(UnmanagedType.Interface), I var projectId = project.ProjectId; - var handler = ProjectRenamed; - if (handler == null || projectId == null) + if (projectId == null) { return; } - handler.Invoke(this, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); + var handler = ProjectRenamed; + handler?.Invoke(this, new ProjectRenamedEventArgs(projectId, project.Name, OldName)); } }