From b65ff6961d4cbfa8ccbc4c286c3cff5cba7a6621 Mon Sep 17 00:00:00 2001 From: Andrii Podkolzin Date: Wed, 28 Sep 2022 16:14:10 +0300 Subject: [PATCH] Refactor solution a bit to make add crossplatform support --- .gitignore | 41 ++- Common/GridMethod.cs | 8 +- Common/OutputHandlerWindow.cs | 19 ++ Common/ThreadWorker.cs | 2 +- Common/UIUtils.cs | 16 + Console/NativeMethods.cs | 2 +- Forms/AboutBox.Designer.cs | 2 +- Forms/AboutBox.cs | 6 +- Forms/ConnectionBox.Designer.cs | 2 +- Forms/ConnectionBox.cs | 11 +- Forms/DatabaseBox.Designer.cs | 2 +- Forms/DatabaseBox.cs | 16 +- Forms/ErrorBox.Designer.cs | 2 +- Forms/ErrorBox.cs | 5 +- Forms/MainBox.Designer.cs | 2 +- Forms/MainBox.cs | 14 +- Forms/SettingsBox.Designer.cs | 2 +- Forms/SettingsBox.cs | 5 +- Forms/SplashScreenBox.Designer.cs | 2 +- Forms/SplashScreenBox.cs | 3 +- Program.cs | 11 +- Properties/Resources.Designer.cs | 36 --- Properties/Resources.resx | 12 - SQLIndexManager.CLI/Program.cs | 17 + .../SQLIndexManager.CLI.csproj | 14 + {Common => SQLIndexManager.Core}/AES.cs | 8 +- {Common => SQLIndexManager.Core}/AppInfo.cs | 2 +- .../CommandLine}/CmdArgument.cs | 3 +- .../CommandLine}/CmdParser.cs | 2 +- .../CommandLine}/CmdWorker.cs | 244 +++++++------- SQLIndexManager.Core/IOutputHandler.cs | 6 + SQLIndexManager.Core/MessageConstants.cs | 70 +++++ {Common => SQLIndexManager.Core}/Output.cs | 26 +- .../SQLIndexManager.Core.csproj | 19 ++ .../Server}/AbortAfterWait.cs | 2 +- .../Server}/AuthTypes.cs | 2 +- .../Server}/ConnectionList.cs | 4 +- .../Server/ConnectionUtils.cs | 6 +- .../Server}/DataCompression.cs | 2 +- .../Server}/Database.cs | 2 +- .../Server}/DiskInfo.cs | 2 +- .../Server}/Host.cs | 2 +- .../Server}/Index.cs | 43 ++- .../Server}/IndexOp.cs | 2 +- .../Server}/IndexType.cs | 2 +- .../Server}/NoRecompute.cs | 2 +- .../Server}/Query.cs | 2 +- .../Server}/QueryEngine.cs | 297 +++++++++--------- .../Server}/ScanMode.cs | 2 +- .../Server}/ServerInfo.cs | 2 +- .../Server}/ServerVersion.cs | 2 +- .../Server}/WarningType.cs | 2 +- .../Settings}/GlobalSettings.cs | 3 +- .../Settings}/Options.cs | 3 +- .../Settings}/Settings.cs | 23 +- {Common => SQLIndexManager.Core}/Utils.cs | 9 +- SQLIndexManager.csproj | 41 +-- SQLIndexManager.sln | 12 + Server/ProgressStatus.cs | 2 +- 59 files changed, 648 insertions(+), 455 deletions(-) create mode 100644 Common/OutputHandlerWindow.cs create mode 100644 Common/UIUtils.cs create mode 100644 SQLIndexManager.CLI/Program.cs create mode 100644 SQLIndexManager.CLI/SQLIndexManager.CLI.csproj rename {Common => SQLIndexManager.Core}/AES.cs (90%) rename {Common => SQLIndexManager.Core}/AppInfo.cs (97%) rename {Console => SQLIndexManager.Core/CommandLine}/CmdArgument.cs (78%) rename {Console => SQLIndexManager.Core/CommandLine}/CmdParser.cs (92%) rename {Console => SQLIndexManager.Core/CommandLine}/CmdWorker.cs (69%) create mode 100644 SQLIndexManager.Core/IOutputHandler.cs create mode 100644 SQLIndexManager.Core/MessageConstants.cs rename {Common => SQLIndexManager.Core}/Output.cs (73%) create mode 100644 SQLIndexManager.Core/SQLIndexManager.Core.csproj rename {Types => SQLIndexManager.Core/Server}/AbortAfterWait.cs (66%) rename {Types => SQLIndexManager.Core/Server}/AuthTypes.cs (59%) rename {Server => SQLIndexManager.Core/Server}/ConnectionList.cs (93%) rename Server/Connection.cs => SQLIndexManager.Core/Server/ConnectionUtils.cs (84%) rename {Types => SQLIndexManager.Core/Server}/DataCompression.cs (77%) rename {Server => SQLIndexManager.Core/Server}/Database.cs (93%) rename {Server => SQLIndexManager.Core/Server}/DiskInfo.cs (81%) rename {Server => SQLIndexManager.Core/Server}/Host.cs (94%) rename {Server => SQLIndexManager.Core/Server}/Index.cs (81%) rename {Types => SQLIndexManager.Core/Server}/IndexOp.cs (97%) rename {Types => SQLIndexManager.Core/Server}/IndexType.cs (80%) rename {Types => SQLIndexManager.Core/Server}/NoRecompute.cs (64%) rename {Server => SQLIndexManager.Core/Server}/Query.cs (99%) rename {Server => SQLIndexManager.Core/Server}/QueryEngine.cs (53%) rename {Types => SQLIndexManager.Core/Server}/ScanMode.cs (66%) rename {Server => SQLIndexManager.Core/Server}/ServerInfo.cs (98%) rename {Types => SQLIndexManager.Core/Server}/ServerVersion.cs (88%) rename {Types => SQLIndexManager.Core/Server}/WarningType.cs (66%) rename {Settings => SQLIndexManager.Core/Settings}/GlobalSettings.cs (77%) rename {Settings => SQLIndexManager.Core/Settings}/Options.cs (99%) rename {Settings => SQLIndexManager.Core/Settings}/Settings.cs (92%) rename {Common => SQLIndexManager.Core}/Utils.cs (92%) diff --git a/.gitignore b/.gitignore index cf8e217..0626272 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,37 @@ -/.vs/ -/Bin/ -/obj/ -*.sln.DotSettings.user +*.swp +*.*~ +project.lock.json +.DS_Store +*.pyc +nupkg/ + +# Visual Studio Code +.vscode + +# Rider +.idea + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +msbuild.log +msbuild.err +msbuild.wrn + +# Visual Studio 2015 +.vs/ \ No newline at end of file diff --git a/Common/GridMethod.cs b/Common/GridMethod.cs index 56ce2b8..d003abd 100644 --- a/Common/GridMethod.cs +++ b/Common/GridMethod.cs @@ -4,11 +4,13 @@ using DevExpress.XtraGrid.Views.Base; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraGrid.Views.Grid.ViewInfo; +using SQLIndexManager.Core; +using SQLIndexManager.Core.Server; using SQLIndexManager.Properties; -namespace SQLIndexManager { +namespace SQLIndexManager.Common { - public class GridMethod: Control { + public static class GridMethod { public static void GridRowCellStyle(object sender, RowCellStyleEventArgs e) { if (e.RowHandle == ((GridView)sender).FocusedRowHandle) { @@ -18,7 +20,7 @@ public static void GridRowCellStyle(object sender, RowCellStyleEventArgs e) { public static void GridDoubleClick(object sender, EventArgs e) { GridView obj = (GridView)sender; - Point pt = obj.GridControl.PointToClient(MousePosition); + Point pt = obj.GridControl.PointToClient(Control.MousePosition); GridHitInfo info = obj.CalcHitInfo(pt); if (info.Column == null || info.Column.Caption == Resources.Fix || info.Column.Caption == Resources.Selection) diff --git a/Common/OutputHandlerWindow.cs b/Common/OutputHandlerWindow.cs new file mode 100644 index 0000000..5ad2269 --- /dev/null +++ b/Common/OutputHandlerWindow.cs @@ -0,0 +1,19 @@ +using DevExpress.XtraBars; +using SQLIndexManager.Core; + +namespace SQLIndexManager.Common { + public class OutputHandlerWindow : IOutputHandler { + + private readonly BarStaticItem _control; + + public OutputHandlerWindow(BarStaticItem control) { + + _control = control; + } + + public void AddCaption(string message) { + + _control.Caption = message; + } + } +} diff --git a/Common/ThreadWorker.cs b/Common/ThreadWorker.cs index 26f9ae3..4f9d902 100644 --- a/Common/ThreadWorker.cs +++ b/Common/ThreadWorker.cs @@ -1,7 +1,7 @@ using System.ComponentModel; using System.Threading; -namespace SQLIndexManager { +namespace SQLIndexManager.Common { public class ThreadWorker : BackgroundWorker { diff --git a/Common/UIUtils.cs b/Common/UIUtils.cs new file mode 100644 index 0000000..3573923 --- /dev/null +++ b/Common/UIUtils.cs @@ -0,0 +1,16 @@ +using System; +using SQLIndexManager.Core; +using SQLIndexManager.Forms; + +namespace SQLIndexManager.Common { + + public static class UIUtils { + + public static void ShowErrorFrom(Exception e, string message = "Error") { + Output.Current.Add($"{message}: {e.Source}", e.Message); + using (ErrorBox errorBox = new ErrorBox(e)) { + errorBox.ShowDialog(); + } + } + } +} diff --git a/Console/NativeMethods.cs b/Console/NativeMethods.cs index d79441a..aba078b 100644 --- a/Console/NativeMethods.cs +++ b/Console/NativeMethods.cs @@ -1,6 +1,6 @@ using System.Runtime.InteropServices; -namespace SQLIndexManager { +namespace SQLIndexManager.Console { public static class NativeMethods { diff --git a/Forms/AboutBox.Designer.cs b/Forms/AboutBox.Designer.cs index 479058c..1de7f03 100644 --- a/Forms/AboutBox.Designer.cs +++ b/Forms/AboutBox.Designer.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { partial class AboutBox { /// /// Required designer variable. diff --git a/Forms/AboutBox.cs b/Forms/AboutBox.cs index d57c39e..877efd7 100644 --- a/Forms/AboutBox.cs +++ b/Forms/AboutBox.cs @@ -3,9 +3,11 @@ using System.Windows.Forms; using DevExpress.Utils; using DevExpress.XtraEditors; +using SQLIndexManager.Common; +using SQLIndexManager.Core; using SQLIndexManager.Properties; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { public partial class AboutBox : XtraForm { @@ -23,7 +25,7 @@ private void GitHub_HyperlinkClick(object sender, HyperlinkClickEventArgs e) { Process.Start(Resources.GitHubLink); } catch (Exception ex) { - Utils.ShowErrorFrom(ex); + UIUtils.ShowErrorFrom(ex); } } diff --git a/Forms/ConnectionBox.Designer.cs b/Forms/ConnectionBox.Designer.cs index 54ed6cd..ac42a4e 100644 --- a/Forms/ConnectionBox.Designer.cs +++ b/Forms/ConnectionBox.Designer.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { partial class ConnectionBox { /// /// Required designer variable. diff --git a/Forms/ConnectionBox.cs b/Forms/ConnectionBox.cs index 8379475..c0f279d 100644 --- a/Forms/ConnectionBox.cs +++ b/Forms/ConnectionBox.cs @@ -4,9 +4,12 @@ using System.Data.SqlClient; using System.Windows.Forms; using DevExpress.XtraEditors; -using SQLIndexManager.Properties; +using SQLIndexManager.Common; +using SQLIndexManager.Core; +using SQLIndexManager.Core.Server; +using SQLIndexManager.Core.Settings; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { public partial class ConnectionBox : XtraForm { @@ -56,7 +59,7 @@ private void CancelConnection() { } private void OpenConnection(object sender, DoWorkEventArgs e) { - SqlConnection connection = Connection.Create(GetHost()); + SqlConnection connection = ConnectionUtils.Create(GetHost()); connection.Open(); e.Result = connection; } @@ -88,7 +91,7 @@ private void CheckConnection(object sender, RunWorkerCompletedEventArgs e) { } if (_serverInfo.MajorVersion < ServerVersion.Sql2008) { - XtraMessageBox.Show(Resources.MinVersionMessage, "", MessageBoxButtons.OK, MessageBoxIcon.Warning); + XtraMessageBox.Show(MessageConstants.MinVersionMessage, "", MessageBoxButtons.OK, MessageBoxIcon.Warning); boxServer.Focus(); } else { diff --git a/Forms/DatabaseBox.Designer.cs b/Forms/DatabaseBox.Designer.cs index a72b948..6112fce 100644 --- a/Forms/DatabaseBox.Designer.cs +++ b/Forms/DatabaseBox.Designer.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { partial class DatabaseBox { /// /// Required designer variable. diff --git a/Forms/DatabaseBox.cs b/Forms/DatabaseBox.cs index 769a13d..d19a1ca 100644 --- a/Forms/DatabaseBox.cs +++ b/Forms/DatabaseBox.cs @@ -9,9 +9,13 @@ using DevExpress.XtraEditors; using DevExpress.XtraGrid.Columns; using DevExpress.XtraGrid.Views.Grid; +using SQLIndexManager.Common; +using SQLIndexManager.Core; +using SQLIndexManager.Core.Server; +using SQLIndexManager.Core.Settings; using SQLIndexManager.Properties; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { public partial class DatabaseBox : XtraForm { @@ -56,24 +60,24 @@ public List GetDatabases() { private Stopwatch _ts = new Stopwatch(); private void ScanDatabases(object sender, DoWorkEventArgs e) { - using (SqlConnection connection = Connection.Create(Settings.ActiveHost)) { + using (SqlConnection connection = ConnectionUtils.Create(Settings.ActiveHost)) { try { connection.Open(); try { _disks = QueryEngine.GetDiskInfo(connection); } - catch (Exception ex) { Utils.ShowErrorFrom(ex, "Refresh disk info failed"); } + catch (Exception ex) { UIUtils.ShowErrorFrom(ex, "Refresh disk info failed"); } try { _databases = QueryEngine.GetDatabases(connection); } - catch (Exception ex) { Utils.ShowErrorFrom(ex, "Refresh databases failed"); } + catch (Exception ex) { UIUtils.ShowErrorFrom(ex, "Refresh databases failed"); } if (_databases.Count > 0 && !Settings.ServerInfo.IsAzure) { try { QueryEngine.RefreshDatabaseSize(connection, _databases); } - catch (Exception ex) { Utils.ShowErrorFrom(ex, "Refresh database sizes failed"); } + catch (Exception ex) { UIUtils.ShowErrorFrom(ex, "Refresh database sizes failed"); } } } catch (Exception ex) { - Utils.ShowErrorFrom(ex, "Refresh failed"); + UIUtils.ShowErrorFrom(ex, "Refresh failed"); } finally { connection.Close(); diff --git a/Forms/ErrorBox.Designer.cs b/Forms/ErrorBox.Designer.cs index e5b6555..f9176fa 100644 --- a/Forms/ErrorBox.Designer.cs +++ b/Forms/ErrorBox.Designer.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { partial class ErrorBox { /// /// Required designer variable. diff --git a/Forms/ErrorBox.cs b/Forms/ErrorBox.cs index c3b5b8d..c01c408 100644 --- a/Forms/ErrorBox.cs +++ b/Forms/ErrorBox.cs @@ -1,9 +1,12 @@ using System; using System.Windows.Forms; using DevExpress.XtraEditors; +using SQLIndexManager.Core; +using SQLIndexManager.Core.Server; +using SQLIndexManager.Core.Settings; using SQLIndexManager.Properties; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { public partial class ErrorBox : XtraForm { diff --git a/Forms/MainBox.Designer.cs b/Forms/MainBox.Designer.cs index f53d4d0..7db73df 100644 --- a/Forms/MainBox.Designer.cs +++ b/Forms/MainBox.Designer.cs @@ -1,6 +1,6 @@ using DevExpress.XtraBars; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { partial class MainBox { private System.ComponentModel.IContainer components = null; diff --git a/Forms/MainBox.cs b/Forms/MainBox.cs index 943df96..39a4a09 100644 --- a/Forms/MainBox.cs +++ b/Forms/MainBox.cs @@ -19,16 +19,22 @@ using DevExpress.XtraGrid.Localization; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraGrid.Views.Grid.ViewInfo; +using SQLIndexManager.Common; +using SQLIndexManager.Core; +using SQLIndexManager.Core.Server; +using SQLIndexManager.Core.Settings; using SQLIndexManager.Properties; +using SQLIndexManager.Server; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { public partial class MainBox : RibbonForm { public MainBox() { InitializeComponent(); - Output.Current.SetOutputControl(labelInfo); + var outputHandler = new OutputHandlerWindow(labelInfo); + Output.Current.AddOutputHandler(outputHandler); Output.Current.Add($"Log folder: {Environment.CurrentDirectory}"); view.CustomColumnDisplayText += GridMethod.GridColumnDisplayText; @@ -129,7 +135,7 @@ private void ScanIndexes(object sender, DoWorkEventArgs e) { } if (!ex.Message.Contains("timeout")) { - Utils.ShowErrorFrom(ex); + UIUtils.ShowErrorFrom(ex); return; } @@ -927,7 +933,7 @@ private void ButtonLog(object sender, ItemClickEventArgs e) { Process.Start(AppInfo.LogFileName); } catch (Exception ex) { - Utils.ShowErrorFrom(ex); + UIUtils.ShowErrorFrom(ex); } } diff --git a/Forms/SettingsBox.Designer.cs b/Forms/SettingsBox.Designer.cs index b7faaa3..16a4222 100644 --- a/Forms/SettingsBox.Designer.cs +++ b/Forms/SettingsBox.Designer.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { partial class SettingsBox { /// /// Required designer variable. diff --git a/Forms/SettingsBox.cs b/Forms/SettingsBox.cs index cf71283..8d04240 100644 --- a/Forms/SettingsBox.cs +++ b/Forms/SettingsBox.cs @@ -3,8 +3,11 @@ using System.Windows.Forms; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Repository; +using SQLIndexManager.Core; +using SQLIndexManager.Core.Server; +using SQLIndexManager.Core.Settings; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { public partial class SettingsBox : XtraForm { diff --git a/Forms/SplashScreenBox.Designer.cs b/Forms/SplashScreenBox.Designer.cs index f80ff2d..9988d2a 100644 --- a/Forms/SplashScreenBox.Designer.cs +++ b/Forms/SplashScreenBox.Designer.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { partial class SplashScreenBox { /// /// Required designer variable. diff --git a/Forms/SplashScreenBox.cs b/Forms/SplashScreenBox.cs index 663a07d..897c930 100644 --- a/Forms/SplashScreenBox.cs +++ b/Forms/SplashScreenBox.cs @@ -1,6 +1,7 @@ using DevExpress.XtraSplashScreen; +using SQLIndexManager.Core; -namespace SQLIndexManager { +namespace SQLIndexManager.Forms { public partial class SplashScreenBox : SplashScreen { diff --git a/Program.cs b/Program.cs index 1ba3380..6f7ba7d 100644 --- a/Program.cs +++ b/Program.cs @@ -5,6 +5,12 @@ using System.Windows.Forms; using DevExpress.LookAndFeel; using DevExpress.XtraSplashScreen; +using SQLIndexManager.Common; +using SQLIndexManager.Console; +using SQLIndexManager.Core; +using SQLIndexManager.Core.CommandLine; +using SQLIndexManager.Core.Settings; +using SQLIndexManager.Forms; namespace SQLIndexManager { @@ -48,7 +54,7 @@ static void Main(string[] args) { } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { - Utils.ShowErrorFrom(e.Exception); + UIUtils.ShowErrorFrom(e.Exception); } private static void AttachConsole() { @@ -66,9 +72,8 @@ private static void AttachConsole() { if (!consoleAttached && !NativeMethods.AllocConsole()) Environment.Exit(1); else - Console.OutputEncoding = (Encoding)Console.OutputEncoding.Clone(); + System.Console.OutputEncoding = (Encoding)System.Console.OutputEncoding.Clone(); } - } } \ No newline at end of file diff --git a/Properties/Resources.Designer.cs b/Properties/Resources.Designer.cs index 48cc45f..29ff179 100644 --- a/Properties/Resources.Designer.cs +++ b/Properties/Resources.Designer.cs @@ -78,15 +78,6 @@ internal static string DatabaseBoxTitle { } } - /// - /// Looks up a localized string similar to DatabaseId. - /// - internal static string DatabaseId { - get { - return ResourceManager.GetString("DatabaseId", resourceCulture); - } - } - /// /// Looks up a localized string similar to DatabaseName. /// @@ -732,15 +723,6 @@ internal static string LogFreeSize { } } - /// - /// Looks up a localized string similar to LogReuseWait. - /// - internal static string LogReuseWait { - get { - return ResourceManager.GetString("LogReuseWait", resourceCulture); - } - } - /// /// Looks up a localized string similar to LogSize. /// @@ -759,15 +741,6 @@ internal static string LogUsedSize { } } - /// - /// Looks up a localized string similar to SQL Server 2000/2005 is not supported.. - /// - internal static string MinVersionMessage { - get { - return ResourceManager.GetString("MinVersionMessage", resourceCulture); - } - } - /// /// Looks up a localized string similar to ModifyDate. /// @@ -858,15 +831,6 @@ internal static string Progress { } } - /// - /// Looks up a localized string similar to RecoveryModel. - /// - internal static string RecoveryModel { - get { - return ResourceManager.GetString("RecoveryModel", resourceCulture); - } - } - /// /// Looks up a localized string similar to RowsCount. /// diff --git a/Properties/Resources.resx b/Properties/Resources.resx index e0068dc..e16a20c 100644 --- a/Properties/Resources.resx +++ b/Properties/Resources.resx @@ -172,9 +172,6 @@ ..\Images\icon_fix.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - RecoveryModel - IndexType @@ -253,9 +250,6 @@ IsAllowPageLocks - - LogReuseWait - Duration @@ -322,9 +316,6 @@ IndexName - - SQL Server 2000/2005 is not supported. - ..\Images\icon.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a @@ -391,9 +382,6 @@ ..\Images\icon_hide.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - DatabaseId - ..\Images\icon_delete.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a diff --git a/SQLIndexManager.CLI/Program.cs b/SQLIndexManager.CLI/Program.cs new file mode 100644 index 0000000..6c79fbb --- /dev/null +++ b/SQLIndexManager.CLI/Program.cs @@ -0,0 +1,17 @@ +// See https://aka.ms/new-console-template for more information + +using SQLIndexManager; +using SQLIndexManager.Core; +using SQLIndexManager.Core.CommandLine; + +Output.Current.AddOutputHandler(new ConsoleOutputHandler()); + +var provider = new CmdWorker(CmdParser.Parse(args)); +return provider.FixIndexes(); + +class ConsoleOutputHandler : IOutputHandler { + + public void AddCaption(string message) { + Console.WriteLine(message); + } +} \ No newline at end of file diff --git a/SQLIndexManager.CLI/SQLIndexManager.CLI.csproj b/SQLIndexManager.CLI/SQLIndexManager.CLI.csproj new file mode 100644 index 0000000..58a92d3 --- /dev/null +++ b/SQLIndexManager.CLI/SQLIndexManager.CLI.csproj @@ -0,0 +1,14 @@ + + + + Exe + net6.0 + enable + enable + + + + + + + diff --git a/Common/AES.cs b/SQLIndexManager.Core/AES.cs similarity index 90% rename from Common/AES.cs rename to SQLIndexManager.Core/AES.cs index 27a8640..cd9a15b 100644 --- a/Common/AES.cs +++ b/SQLIndexManager.Core/AES.cs @@ -3,14 +3,14 @@ using System.Security.Cryptography; using System.Text; -namespace SQLIndexManager { +namespace SQLIndexManager.Core { - internal class AES { + public class AES { private static readonly byte[] Key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; private static readonly byte[] Key2 = Encoding.UTF8.GetBytes("_SQLIndexManager"); - internal static string Encrypt(string content) { + public static string Encrypt(string content) { using (Rijndael des = Rijndael.Create()) { var input = Encoding.UTF8.GetBytes(content); des.Key = Key2; @@ -28,7 +28,7 @@ internal static string Encrypt(string content) { } } - internal static string Decrypt(string content) { + public static string Decrypt(string content) { using (Rijndael des = Rijndael.Create()) { des.Key = Key2; des.IV = Key1; diff --git a/Common/AppInfo.cs b/SQLIndexManager.Core/AppInfo.cs similarity index 97% rename from Common/AppInfo.cs rename to SQLIndexManager.Core/AppInfo.cs index 85fd5ba..9d1d950 100644 --- a/Common/AppInfo.cs +++ b/SQLIndexManager.Core/AppInfo.cs @@ -2,7 +2,7 @@ using System.IO; using System.Reflection; -namespace SQLIndexManager { +namespace SQLIndexManager.Core { public static class AppInfo { diff --git a/Console/CmdArgument.cs b/SQLIndexManager.Core/CommandLine/CmdArgument.cs similarity index 78% rename from Console/CmdArgument.cs rename to SQLIndexManager.Core/CommandLine/CmdArgument.cs index 541a4aa..ba656fd 100644 --- a/Console/CmdArgument.cs +++ b/SQLIndexManager.Core/CommandLine/CmdArgument.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.CommandLine { public class CmdArgument { public string Argument; public readonly List Params = new List(); - } } diff --git a/Console/CmdParser.cs b/SQLIndexManager.Core/CommandLine/CmdParser.cs similarity index 92% rename from Console/CmdParser.cs rename to SQLIndexManager.Core/CommandLine/CmdParser.cs index 23e4ed7..534d67c 100644 --- a/Console/CmdParser.cs +++ b/SQLIndexManager.Core/CommandLine/CmdParser.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.CommandLine { public static class CmdParser { diff --git a/Console/CmdWorker.cs b/SQLIndexManager.Core/CommandLine/CmdWorker.cs similarity index 69% rename from Console/CmdWorker.cs rename to SQLIndexManager.Core/CommandLine/CmdWorker.cs index a43b09e..aaf4ca4 100644 --- a/Console/CmdWorker.cs +++ b/SQLIndexManager.Core/CommandLine/CmdWorker.cs @@ -1,131 +1,41 @@ -using SQLIndexManager.Properties; -using System; +using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; +using SQLIndexManager.Core.Server; +using Index = SQLIndexManager.Core.Server.Index; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.CommandLine { public class CmdWorker { public CmdWorker(List args) { - Host host = new Host(); - Settings.Options.IgnorePermissions = false; - Settings.Options.IgnoreReadOnlyFL = false; - - foreach (CmdArgument cmd in args) { - switch (cmd.Argument) { - case "connection": - SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(cmd.Params[0]); - host.Server = sb.DataSource; - host.AuthType = sb.IntegratedSecurity ? AuthTypes.Windows : AuthTypes.Sql; - host.User = sb.UserID; - if (!string.IsNullOrEmpty(sb.InitialCatalog)) { - host.Databases.Add(sb.InitialCatalog); - } - if (!sb.IntegratedSecurity) { - host.Password = sb.Password; - } - Settings.Options.ConnectionTimeout = sb.ConnectTimeout; - break; - - case "databases": - host.Databases.Clear(); - List dbs = new List (cmd.Params[0].Split(';')); - host.Databases.AddRange(dbs.Where(_ => !string.IsNullOrEmpty(_)).Distinct()); - break; - - case "connectiontimeout": - Settings.Options.ConnectionTimeout = Convert.ToInt32(cmd.Params[0]); - break; - - case "commandtimeout": - Settings.Options.CommandTimeout = Convert.ToInt32(cmd.Params[0]); - break; - - case "online": - Settings.Options.Online = true; - break; - - case "missingindex": - Settings.Options.ScanMissingIndex = true; - break; - - case "ignoreheap": - Settings.Options.ScanHeap = false; - break; - - case "ignorecolumnstore": - Settings.Options.ScanClusteredColumnstore = false; - Settings.Options.ScanNonClusteredColumnstore = false; - break; - - case "ignorebtree": - Settings.Options.ScanClusteredIndex = false; - Settings.Options.ScanNonClusteredIndex = false; - break; - - case "maxdop": - Settings.Options.MaxDop = Convert.ToInt32(cmd.Params[0]); - break; - - case "rebuildthreshold": - Settings.Options.SecondThreshold = Convert.ToInt32(cmd.Params[0]); - break; - - case "reorganizethreshold": - Settings.Options.FirstThreshold = Convert.ToInt32(cmd.Params[0]); - break; - - case "minindexsize": - Settings.Options.MinIndexSize = Convert.ToInt32(cmd.Params[0]); - break; - - case "predescribesize": - Settings.Options.PreDescribeSize = Convert.ToInt32(cmd.Params[0]); - break; - - case "maxindexsize": - Settings.Options.MaxIndexSize = Convert.ToInt32(cmd.Params[0]); - break; - - default: - throw new ArgumentException($"Unknown argument \"{cmd.Argument}\""); - } - } - + + var host = SetupSettings(args); + if (host.Databases.Count == 0) throw new ArgumentException("No database selected"); - using (SqlConnection connection = Connection.Create(host)) { - try { - host.ServerInfo = QueryEngine.GetServerInfo(connection); - } - catch (Exception ex) { - throw new ArgumentException(ex.Message.Replace(". ", "." + Environment.NewLine)); - } - finally { - connection.Close(); - } - } - + host.ServerInfo = GetServerInfo(host); + if (host.ServerInfo.MajorVersion < ServerVersion.Sql2008) - throw new ArgumentException(Resources.MinVersionMessage); + throw new ArgumentException(MessageConstants.MinVersionMessage); else - Settings.ActiveHost = host; + Settings.Settings.ActiveHost = host; } public int FixIndexes() { - Output.Current.Add($"Host: {Settings.ActiveHost}"); + + Output.Current.Add($"Host: {Settings.Settings.ActiveHost}"); - using (ConnectionList connectionList = new ConnectionList(Settings.ActiveHost)) { + using (ConnectionList connectionList = new ConnectionList(Settings.Settings.ActiveHost)) { List scanIndex = new List(); Stopwatch watch; Stopwatch totalWatch = Stopwatch.StartNew(); - foreach (var database in Settings.ActiveHost.Databases) { + foreach (var database in Settings.Settings.ActiveHost.Databases) { List idx = new List(); watch = Stopwatch.StartNew(); SqlConnection connection = connectionList.Get(database); @@ -189,9 +99,9 @@ public int FixIndexes() { scanIndex.AddRange(idx); } - var fixIndex = scanIndex.Where(_ => _.Fragmentation >= Settings.Options.FirstThreshold - && _.PagesCount >= Settings.Options.MinIndexSize.PageSize() - && _.PagesCount <= Settings.Options.MaxIndexSize.PageSize()).ToList(); + var fixIndex = scanIndex.Where(_ => _.Fragmentation >= Settings.Settings.Options.FirstThreshold + && _.PagesCount >= Settings.Settings.Options.MinIndexSize.PageSize() + && _.PagesCount <= Settings.Settings.Options.MaxIndexSize.PageSize()).ToList(); Output.Current.Add(new string('-', 150)); Output.Current.Add($"Processed: {scanIndex.Count}. Fragmented: {fixIndex.Count}", null, totalWatch.ElapsedMilliseconds); @@ -203,9 +113,9 @@ public int FixIndexes() { foreach (Index ix in fixIndex) { if (ix.IndexType == IndexType.MISSING_INDEX) ix.FixType = IndexOp.CREATE_INDEX; - else if (ix.Fragmentation < Settings.Options.SecondThreshold && ix.IsAllowReorganize) + else if (ix.Fragmentation < Settings.Settings.Options.SecondThreshold && ix.IsAllowReorganize) ix.FixType = IndexOp.REORGANIZE; - else if (Settings.Options.Online && ix.IsAllowOnlineRebuild) + else if (Settings.Settings.Options.Online && ix.IsAllowOnlineRebuild) ix.FixType = IndexOp.REBUILD_ONLINE; else ix.FixType = IndexOp.REBUILD; @@ -235,6 +145,120 @@ public int FixIndexes() { return 0; } + private static ServerInfo GetServerInfo(Host host) + { + using (SqlConnection connection = ConnectionUtils.Create(host)) + { + try + { + return QueryEngine.GetServerInfo(connection); + } + catch (Exception ex) + { + throw new ArgumentException(ex.Message.Replace(". ", "." + Environment.NewLine)); + } + finally + { + connection.Close(); + } + } + } + + private static Host SetupSettings(List args) + { + Host host = new Host(); + Settings.Settings.Options.IgnorePermissions = false; + Settings.Settings.Options.IgnoreReadOnlyFL = false; + + foreach (CmdArgument cmd in args) + { + switch (cmd.Argument) + { + case "connection": + SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(cmd.Params[0]); + host.Server = sb.DataSource; + host.AuthType = sb.IntegratedSecurity ? AuthTypes.Windows : AuthTypes.Sql; + host.User = sb.UserID; + if (!string.IsNullOrEmpty(sb.InitialCatalog)) + { + host.Databases.Add(sb.InitialCatalog); + } + + if (!sb.IntegratedSecurity) + { + host.Password = sb.Password; + } + + Settings.Settings.Options.ConnectionTimeout = sb.ConnectTimeout; + break; + + case "databases": + host.Databases.Clear(); + List dbs = new List(cmd.Params[0].Split(';')); + host.Databases.AddRange(dbs.Where(_ => !string.IsNullOrEmpty(_)).Distinct()); + break; + + case "connectiontimeout": + Settings.Settings.Options.ConnectionTimeout = Convert.ToInt32(cmd.Params[0]); + break; + + case "commandtimeout": + Settings.Settings.Options.CommandTimeout = Convert.ToInt32(cmd.Params[0]); + break; + + case "online": + Settings.Settings.Options.Online = true; + break; + + case "missingindex": + Settings.Settings.Options.ScanMissingIndex = true; + break; + + case "ignoreheap": + Settings.Settings.Options.ScanHeap = false; + break; + + case "ignorecolumnstore": + Settings.Settings.Options.ScanClusteredColumnstore = false; + Settings.Settings.Options.ScanNonClusteredColumnstore = false; + break; + + case "ignorebtree": + Settings.Settings.Options.ScanClusteredIndex = false; + Settings.Settings.Options.ScanNonClusteredIndex = false; + break; + + case "maxdop": + Settings.Settings.Options.MaxDop = Convert.ToInt32(cmd.Params[0]); + break; + + case "rebuildthreshold": + Settings.Settings.Options.SecondThreshold = Convert.ToInt32(cmd.Params[0]); + break; + + case "reorganizethreshold": + Settings.Settings.Options.FirstThreshold = Convert.ToInt32(cmd.Params[0]); + break; + + case "minindexsize": + Settings.Settings.Options.MinIndexSize = Convert.ToInt32(cmd.Params[0]); + break; + + case "predescribesize": + Settings.Settings.Options.PreDescribeSize = Convert.ToInt32(cmd.Params[0]); + break; + + case "maxindexsize": + Settings.Settings.Options.MaxIndexSize = Convert.ToInt32(cmd.Params[0]); + break; + + default: + throw new ArgumentException($"Unknown argument \"{cmd.Argument}\""); + } + } + + return host; + } } } \ No newline at end of file diff --git a/SQLIndexManager.Core/IOutputHandler.cs b/SQLIndexManager.Core/IOutputHandler.cs new file mode 100644 index 0000000..72eb820 --- /dev/null +++ b/SQLIndexManager.Core/IOutputHandler.cs @@ -0,0 +1,6 @@ +namespace SQLIndexManager.Core { + public interface IOutputHandler { + + void AddCaption(string message); + } +} diff --git a/SQLIndexManager.Core/MessageConstants.cs b/SQLIndexManager.Core/MessageConstants.cs new file mode 100644 index 0000000..a749361 --- /dev/null +++ b/SQLIndexManager.Core/MessageConstants.cs @@ -0,0 +1,70 @@ +namespace SQLIndexManager.Core; + +public static class MessageConstants +{ + public const string CreateDate = "CreateDate"; + public const string DatabaseBoxTitle = "Databases"; + public const string DatabaseId = "DatabaseId"; + public const string DatabaseName = "DatabaseName"; + public const string DataCompression = "DataCompression"; + public const string DataFreeSize = "DataFreeSize"; + public const string DatamaseMaster = "master"; + public const string DataSize = "DataSize"; + public const string DataUsedSize = "DataUsedSize"; + public const string Duration = "Duration"; + public const string Edition = "Edition"; + public const string FileGroupName = "FileGroupName"; + public const string FillFactor = "FillFactorValue"; + public const string Fix = "Fix"; + public const string FixType = "FixType"; + public const string Fragmentation = "Fragmentation"; + public const string GitHubLink = "www.github.com/sergiisyrovatchenko/SQLIndexManager"; + public const string IncludedColumns = "IncludedColumns"; + public const string IndexColumns = "IndexColumns"; + public const string IndexID = "IndexID"; + public const string IndexName = "IndexName"; + public const string IndexStats = "IndexStats"; + public const string IndexType = "IndexType"; + public const string IsAllowPageLocks = "IsAllowPageLocks"; + public const string IsFiltered = "IsFiltered"; + public const string IsFKs = "IsFKs"; + public const string IsLob = "IsLob"; + public const string IsLobLegacy = "IsLobLegacy"; + public const string IsNoRecompute = "IsNoRecompute"; + public const string IsPartitioned = "IsPartitioned"; + public const string IsPK = "IsPK"; + public const string IsSparse = "IsSparse"; + public const string IsSysAdmin = "IsSysAdmin"; + public const string IsTable = "IsTable"; + public const string IsUnique = "IsUnique"; + public const string LastRead = "LastRead"; + public const string LastWrite = "LastWrite"; + public const string LogFreeSize = "LogFreeSize"; + public const string LogReuseWait = "LogReuseWait"; + public const string LogSize = "LogSize"; + public const string LogUsedSize = "LogUsedSize"; + public const string MinVersionMessage = "SQL Server 2000/2005 is not supported."; + public const string ModifyDate = "ModifyDate"; + public const string ObjectID = "ObjectID"; + public const string ObjectName = "ObjectName"; + public const string PagesCount = "PagesCount"; + public const string PagesCountBefore = "PagesCountBefore"; + public const string PageSpaceUsed = "PageSpaceUsed"; + public const string PartitionNumber = "PartitionNumber"; + public const string ProductLevel = "ProductLevel"; + public const string ProductUpdateLevel = "ProductUpdateLevel"; + public const string Progress = "Progress"; + public const string RecoveryModel = "RecoveryModel"; + public const string RowsCount = "RowsCount"; + public const string RowsSampled = "RowsSampled"; + public const string SchemaName = "SchemaName"; + public const string Selection = "Selection"; + public const string ServerName = "ServerName"; + public const string ServerVersion = "ServerVersion"; + public const string StatsSampled = "StatsSampled"; + public const string TotalLookups = "TotalLookups"; + public const string TotalScans = "TotalScans"; + public const string TotalSeeks = "TotalSeeks"; + public const string TotalUpdates = "TotalUpdates"; + public const string UnusedPagesCount = "UnusedPagesCount"; +} \ No newline at end of file diff --git a/Common/Output.cs b/SQLIndexManager.Core/Output.cs similarity index 73% rename from Common/Output.cs rename to SQLIndexManager.Core/Output.cs index ca08b91..10f2632 100644 --- a/Common/Output.cs +++ b/SQLIndexManager.Core/Output.cs @@ -1,8 +1,8 @@ using System; +using System.Collections.Generic; using System.IO; -using DevExpress.XtraBars; -namespace SQLIndexManager { +namespace SQLIndexManager.Core { public class OutputEvent { @@ -13,11 +13,10 @@ public class OutputEvent { } public class Output { + + private readonly List _outputs = new (); - private static Output _log; - private BarStaticItem _control; - - public static Output Current => _log ?? (_log = new Output()); + public static Output Current { get; } = new (); private Output() { if (File.Exists(AppInfo.LogFileName)) { @@ -28,13 +27,14 @@ private Output() { } } - public void SetOutputControl(BarStaticItem control) { - _control = control; + public void AddOutputHandler(IOutputHandler outputHandler) { + + _outputs.Add(outputHandler); } public void AddCaption(string message) { try { - _control.Caption = message; + _outputs.ForEach(x => x.AddCaption(message)); } catch { } } @@ -45,7 +45,7 @@ public void Add(string message, string message2 = null, long? elapsedMillisecond string msg = message; if (elapsedMilliseconds >= 0) { - duration = (new DateTime(0)).AddMilliseconds((double) elapsedMilliseconds); + duration = (new DateTime(0)).AddMilliseconds((double)elapsedMilliseconds); msg = $"Elapsed time: {duration:HH:mm:ss:fff}. {message}"; } @@ -56,9 +56,7 @@ public void Add(string message, string message2 = null, long? elapsedMillisecond }; try { - if (_control != null) { - _control.Caption = msg; - } + AddCaption(msg); using (StreamWriter sw = File.AppendText(AppInfo.LogFileName)) { sw.WriteLine($"{now:HH:mm:ss.fff} - {msg}"); @@ -71,4 +69,4 @@ public void Add(string message, string message2 = null, long? elapsedMillisecond } -} \ No newline at end of file +} diff --git a/SQLIndexManager.Core/SQLIndexManager.Core.csproj b/SQLIndexManager.Core/SQLIndexManager.Core.csproj new file mode 100644 index 0000000..45bbf55 --- /dev/null +++ b/SQLIndexManager.Core/SQLIndexManager.Core.csproj @@ -0,0 +1,19 @@ + + + + net6.0;net4.5 + disable + enable + 10.0 + + + + + + + + + + + + diff --git a/Types/AbortAfterWait.cs b/SQLIndexManager.Core/Server/AbortAfterWait.cs similarity index 66% rename from Types/AbortAfterWait.cs rename to SQLIndexManager.Core/Server/AbortAfterWait.cs index b2d95f5..7703085 100644 --- a/Types/AbortAfterWait.cs +++ b/SQLIndexManager.Core/Server/AbortAfterWait.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum AbortAfterWait { NONE = 0, diff --git a/Types/AuthTypes.cs b/SQLIndexManager.Core/Server/AuthTypes.cs similarity index 59% rename from Types/AuthTypes.cs rename to SQLIndexManager.Core/Server/AuthTypes.cs index 9c85f7d..ba3280b 100644 --- a/Types/AuthTypes.cs +++ b/SQLIndexManager.Core/Server/AuthTypes.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum AuthTypes { Windows = 0, diff --git a/Server/ConnectionList.cs b/SQLIndexManager.Core/Server/ConnectionList.cs similarity index 93% rename from Server/ConnectionList.cs rename to SQLIndexManager.Core/Server/ConnectionList.cs index 6f50dc0..22c6f42 100644 --- a/Server/ConnectionList.cs +++ b/SQLIndexManager.Core/Server/ConnectionList.cs @@ -4,7 +4,7 @@ using System.Data.SqlClient; using System.Threading; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public class ConnectionList : IDisposable { @@ -13,7 +13,7 @@ public class ConnectionList : IDisposable { public ConnectionList(Host host) { foreach(string database in host.Databases) { - SqlConnection connection = Connection.Create(host, database); + SqlConnection connection = ConnectionUtils.Create(host, database); _databases.Add(database, connection); } } diff --git a/Server/Connection.cs b/SQLIndexManager.Core/Server/ConnectionUtils.cs similarity index 84% rename from Server/Connection.cs rename to SQLIndexManager.Core/Server/ConnectionUtils.cs index 514b239..7841bd3 100644 --- a/Server/Connection.cs +++ b/SQLIndexManager.Core/Server/ConnectionUtils.cs @@ -1,14 +1,14 @@ using System.Data.SqlClient; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { - public static class Connection { + public static class ConnectionUtils { private static string GetConnectionString(Host host, string database) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder() { ApplicationName = AppInfo.ApplicationName, - ConnectTimeout = Settings.Options.ConnectionTimeout, + ConnectTimeout = Settings.Settings.Options.ConnectionTimeout, DataSource = host.Server, InitialCatalog = database ?? "master" }; diff --git a/Types/DataCompression.cs b/SQLIndexManager.Core/Server/DataCompression.cs similarity index 77% rename from Types/DataCompression.cs rename to SQLIndexManager.Core/Server/DataCompression.cs index ef04f34..636625c 100644 --- a/Types/DataCompression.cs +++ b/SQLIndexManager.Core/Server/DataCompression.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum DataCompression { DEFAULT = -1, diff --git a/Server/Database.cs b/SQLIndexManager.Core/Server/Database.cs similarity index 93% rename from Server/Database.cs rename to SQLIndexManager.Core/Server/Database.cs index 4db4260..d2b392f 100644 --- a/Server/Database.cs +++ b/SQLIndexManager.Core/Server/Database.cs @@ -1,6 +1,6 @@ using System; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public class Database { diff --git a/Server/DiskInfo.cs b/SQLIndexManager.Core/Server/DiskInfo.cs similarity index 81% rename from Server/DiskInfo.cs rename to SQLIndexManager.Core/Server/DiskInfo.cs index 6dbd06a..a7c5856 100644 --- a/Server/DiskInfo.cs +++ b/SQLIndexManager.Core/Server/DiskInfo.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public class DiskInfo { diff --git a/Server/Host.cs b/SQLIndexManager.Core/Server/Host.cs similarity index 94% rename from Server/Host.cs rename to SQLIndexManager.Core/Server/Host.cs index 760b1e3..8483407 100644 --- a/Server/Host.cs +++ b/SQLIndexManager.Core/Server/Host.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Xml.Serialization; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { [Serializable] public class Host { diff --git a/Server/Index.cs b/SQLIndexManager.Core/Server/Index.cs similarity index 81% rename from Server/Index.cs rename to SQLIndexManager.Core/Server/Index.cs index 23470aa..0410176 100644 --- a/Server/Index.cs +++ b/SQLIndexManager.Core/Server/Index.cs @@ -1,7 +1,6 @@ using System; -using System.Drawing; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public class Index { @@ -54,7 +53,7 @@ public class Index { public bool IsColumnstore => (IndexType == IndexType.CLUSTERED_COLUMNSTORE || IndexType == IndexType.NONCLUSTERED_COLUMNSTORE); public string Error { get; set; } - public Image Progress { get; set; } + public object Progress { get; set; } public long? Duration { get; set; } public IndexOp FixType { get; set; } public WarningType? Warning { get; set; } @@ -78,7 +77,7 @@ public string GetQuery() { case IndexOp.REBUILD_COLUMNSTORE_ARCHIVE: DataCompression compression = (FixType == IndexOp.REBUILD_COLUMNSTORE) ? DataCompression.COLUMNSTORE : DataCompression.COLUMNSTORE_ARCHIVE; sql = $"ALTER INDEX {fullIndexName} REBUILD PARTITION = {partition}{Environment.NewLine} " + - $"WITH (DATA_COMPRESSION = {(FixType == IndexOp.REBUILD ? DataCompression : compression)}, MAXDOP = {Settings.Options.MaxDop});"; + $"WITH (DATA_COMPRESSION = {(FixType == IndexOp.REBUILD ? DataCompression : compression)}, MAXDOP = {Settings.Settings.Options.MaxDop});"; break; case IndexOp.REORGANIZE: @@ -113,17 +112,17 @@ public string GetQuery() { compression = DataCompression.ROW; else if (FixType == IndexOp.REBUILD_NONE) compression = DataCompression.NONE; - else if (Settings.Options.DataCompression != DataCompression.DEFAULT && FixType != IndexOp.REBUILD) - compression = Settings.Options.DataCompression; + else if (Settings.Settings.Options.DataCompression != DataCompression.DEFAULT && FixType != IndexOp.REBUILD) + compression = Settings.Settings.Options.DataCompression; else compression = DataCompression; string onlineRebuild = "OFF"; - if (FixType == IndexOp.REBUILD_ONLINE || (Settings.Options.Online && IsAllowOnlineRebuild)) { - if (Settings.Options.WaitAtLowPriority && Settings.ServerInfo.MajorVersion >= ServerVersion.Sql2014) + if (FixType == IndexOp.REBUILD_ONLINE || (Settings.Settings.Options.Online && IsAllowOnlineRebuild)) { + if (Settings.Settings.Options.WaitAtLowPriority && Settings.Settings.ServerInfo.MajorVersion >= ServerVersion.Sql2014) onlineRebuild = "ON (" + - $"WAIT_AT_LOW_PRIORITY (MAX_DURATION = {Settings.Options.MaxDuration} MINUTES, " + - $"ABORT_AFTER_WAIT = {Settings.Options.AbortAfterWait}))"; + $"WAIT_AT_LOW_PRIORITY (MAX_DURATION = {Settings.Settings.Options.MaxDuration} MINUTES, " + + $"ABORT_AFTER_WAIT = {Settings.Settings.Options.AbortAfterWait}))"; else onlineRebuild = "ON"; } @@ -137,36 +136,36 @@ public string GetQuery() { else sqlHeader = $"ALTER INDEX {fullIndexName} REBUILD PARTITION = {partition}{Environment.NewLine} "; - string nr = Settings.Options.NoRecompute == NoRecompute.DEFAULT + string nr = Settings.Settings.Options.NoRecompute == NoRecompute.DEFAULT ? ((IsNoRecompute ?? false) ? "ON" : "OFF") - : Settings.Options.NoRecompute.ToString(); + : Settings.Settings.Options.NoRecompute.ToString(); sql = sqlHeader + "WITH (" + (IndexType == IndexType.HEAP ? "" - : $"SORT_IN_TEMPDB = {Settings.Options.SortInTempDb.OnOff()}, ") + + : $"SORT_IN_TEMPDB = {Settings.Settings.Options.SortInTempDb.OnOff()}, ") + (IsPartitioned || IndexType == IndexType.HEAP ? "" - : $"PAD_INDEX = {Settings.Options.PadIndex.OnOff()}, ") + - (IsPartitioned || Settings.Options.FillFactor == 0 + : $"PAD_INDEX = {Settings.Settings.Options.PadIndex.OnOff()}, ") + + (IsPartitioned || Settings.Settings.Options.FillFactor == 0 ? "" - : $"FILLFACTOR = {Settings.Options.FillFactor}, ") + + : $"FILLFACTOR = {Settings.Settings.Options.FillFactor}, ") + (IndexType == IndexType.HEAP || IsPartitioned ? "" : $"STATISTICS_NORECOMPUTE = {nr}, ") + (!IsAllowCompression ? "" : $"DATA_COMPRESSION = {compression}, ") + - (Settings.ServerInfo.MajorVersion <= ServerVersion.Sql2012 && IsPartitioned // 'ONLINE' is not a recognized ALTER INDEX REBUILD PARTITION option + (Settings.Settings.ServerInfo.MajorVersion <= ServerVersion.Sql2012 && IsPartitioned // 'ONLINE' is not a recognized ALTER INDEX REBUILD PARTITION option ? "" : $"ONLINE = {onlineRebuild}, ") + - $"MAXDOP = {Settings.Options.MaxDop});"; + $"MAXDOP = {Settings.Settings.Options.MaxDop});"; break; case IndexOp.REORGANIZE: sql = $"ALTER INDEX {fullIndexName} REORGANIZE PARTITION = {partition}{Environment.NewLine} " + - $"WITH (LOB_COMPACTION = {Settings.Options.LobCompaction.OnOff()});"; + $"WITH (LOB_COMPACTION = {Settings.Settings.Options.LobCompaction.OnOff()});"; break; case IndexOp.DISABLE_INDEX: @@ -190,14 +189,14 @@ public string GetQuery() { case IndexOp.UPDATE_STATISTICS_SAMPLE: case IndexOp.UPDATE_STATISTICS_RESAMPLE: case IndexOp.UPDATE_STATISTICS_FULL: - string nr2 = (Settings.Options.NoRecompute == NoRecompute.DEFAULT && (IsNoRecompute ?? false)) - || Settings.Options.NoRecompute == NoRecompute.ON + string nr2 = (Settings.Settings.Options.NoRecompute == NoRecompute.DEFAULT && (IsNoRecompute ?? false)) + || Settings.Settings.Options.NoRecompute == NoRecompute.ON ? ", NORECOMPUTE" : ""; sql = $"UPDATE STATISTICS {objectName} {indexName}{Environment.NewLine} " + ( FixType == IndexOp.UPDATE_STATISTICS_SAMPLE - ? $"WITH SAMPLE {Settings.Options.SampleStatsPercent} PERCENT{nr2};" + ? $"WITH SAMPLE {Settings.Settings.Options.SampleStatsPercent} PERCENT{nr2};" : (FixType == IndexOp.UPDATE_STATISTICS_FULL ? $"WITH FULLSCAN{nr2};" : $"WITH RESAMPLE{nr2};") ); break; diff --git a/Types/IndexOp.cs b/SQLIndexManager.Core/Server/IndexOp.cs similarity index 97% rename from Types/IndexOp.cs rename to SQLIndexManager.Core/Server/IndexOp.cs index 87c7813..fdc4224 100644 --- a/Types/IndexOp.cs +++ b/SQLIndexManager.Core/Server/IndexOp.cs @@ -1,6 +1,6 @@ using System.ComponentModel; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum IndexOp { [Description("REBUILD")] diff --git a/Types/IndexType.cs b/SQLIndexManager.Core/Server/IndexType.cs similarity index 80% rename from Types/IndexType.cs rename to SQLIndexManager.Core/Server/IndexType.cs index 923460a..28ee98c 100644 --- a/Types/IndexType.cs +++ b/SQLIndexManager.Core/Server/IndexType.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum IndexType { MISSING_INDEX = -1, diff --git a/Types/NoRecompute.cs b/SQLIndexManager.Core/Server/NoRecompute.cs similarity index 64% rename from Types/NoRecompute.cs rename to SQLIndexManager.Core/Server/NoRecompute.cs index 2b630e7..5beedb8 100644 --- a/Types/NoRecompute.cs +++ b/SQLIndexManager.Core/Server/NoRecompute.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum NoRecompute { DEFAULT = 0, diff --git a/Server/Query.cs b/SQLIndexManager.Core/Server/Query.cs similarity index 99% rename from Server/Query.cs rename to SQLIndexManager.Core/Server/Query.cs index a5fa5f7..599b834 100644 --- a/Server/Query.cs +++ b/SQLIndexManager.Core/Server/Query.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public class Query { diff --git a/Server/QueryEngine.cs b/SQLIndexManager.Core/Server/QueryEngine.cs similarity index 53% rename from Server/QueryEngine.cs rename to SQLIndexManager.Core/Server/QueryEngine.cs index 641ab4a..5ee3c01 100644 --- a/Server/QueryEngine.cs +++ b/SQLIndexManager.Core/Server/QueryEngine.cs @@ -3,14 +3,13 @@ using System.Data; using System.Data.SqlClient; using System.Linq; -using SQLIndexManager.Properties; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public static class QueryEngine { public static List GetDatabases(SqlConnection connection) { - SqlCommand cmd = new SqlCommand(Query.DatabaseList, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(Query.DatabaseList, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); @@ -20,11 +19,11 @@ public static List GetDatabases(SqlConnection connection) { foreach (DataRow r in data.Tables[0].Rows) { dbs.Add( new Database { - DatabaseId = r.Field(Resources.DatabaseId), - DatabaseName = r.Field(Resources.DatabaseName), - RecoveryModel = r.Field(Resources.RecoveryModel), - LogReuseWait = r.Field(Resources.LogReuseWait), - CreateDate = r.Field(Resources.CreateDate) + DatabaseId = r.Field(MessageConstants.DatabaseId), + DatabaseName = r.Field(MessageConstants.DatabaseName), + RecoveryModel = r.Field(MessageConstants.RecoveryModel), + LogReuseWait = r.Field(MessageConstants.LogReuseWait), + CreateDate = r.Field(MessageConstants.CreateDate) } ); } @@ -33,21 +32,21 @@ public static List GetDatabases(SqlConnection connection) { } public static List RefreshDatabaseSize(SqlConnection connection, List dbs) { - SqlCommand cmd = new SqlCommand(Query.DatabaseSizeList, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(Query.DatabaseSizeList, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); adapter.Fill(data); foreach (DataRow r in data.Tables[0].Rows) { - int databaseId = r.Field(Resources.DatabaseId); + int databaseId = r.Field(MessageConstants.DatabaseId); Database db = dbs.FirstOrDefault(_ => _.DatabaseId == databaseId); if (db != null) { - db.DataSize = r.Field(Resources.DataSize) ?? 0; - db.DataUsedSize = r.Field(Resources.DataUsedSize) ?? 0; - db.LogSize = r.Field(Resources.LogSize) ?? 0; - db.LogUsedSize = r.Field(Resources.LogUsedSize) ?? 0; + db.DataSize = r.Field(MessageConstants.DataSize) ?? 0; + db.DataUsedSize = r.Field(MessageConstants.DataUsedSize) ?? 0; + db.LogSize = r.Field(MessageConstants.LogSize) ?? 0; + db.LogUsedSize = r.Field(MessageConstants.LogUsedSize) ?? 0; } } @@ -57,8 +56,8 @@ public static List RefreshDatabaseSize(SqlConnection connection, List< public static List GetDiskInfo(SqlConnection connection) { List di = new List(); - if (!Settings.ServerInfo.IsAzure && Settings.ServerInfo.IsSysAdmin) { - SqlCommand cmd = new SqlCommand(Query.DiskInfo, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + if (!Settings.Settings.ServerInfo.IsAzure && Settings.Settings.ServerInfo.IsSysAdmin) { + SqlCommand cmd = new SqlCommand(Query.DiskInfo, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); @@ -80,57 +79,57 @@ public static List GetDiskInfo(SqlConnection connection) { public static ServerInfo GetServerInfo(SqlConnection connection) { DataSet data = new DataSet(); - SqlCommand cmd = new SqlCommand(Query.ServerInfo, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(Query.ServerInfo, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(data); DataRow row = data.Tables[0].Rows[0]; - string serverName = row.Field(Resources.ServerName); - string productLevel = row.Field(Resources.ProductLevel); - string productUpdateLevel = row.Field(Resources.ProductUpdateLevel); - string edition = row.Field(Resources.Edition); - string serverVersion = row.Field(Resources.ServerVersion); - bool isSysAdmin = row.Field(Resources.IsSysAdmin) ?? false; + string serverName = row.Field(MessageConstants.ServerName); + string productLevel = row.Field(MessageConstants.ProductLevel); + string productUpdateLevel = row.Field(MessageConstants.ProductUpdateLevel); + string edition = row.Field(MessageConstants.Edition); + string serverVersion = row.Field(MessageConstants.ServerVersion); + bool isSysAdmin = row.Field(MessageConstants.IsSysAdmin) ?? false; return new ServerInfo(serverName, productLevel, productUpdateLevel, edition, serverVersion, isSysAdmin); } public static List GetIndexes(SqlConnection connection) { List it = new List(); - if (Settings.Options.ScanHeap) it.Add((int)IndexType.HEAP); - if (Settings.Options.ScanClusteredIndex) it.Add((int)IndexType.CLUSTERED); - if (Settings.Options.ScanNonClusteredIndex) it.Add((int)IndexType.NONCLUSTERED); + if (Settings.Settings.Options.ScanHeap) it.Add((int)IndexType.HEAP); + if (Settings.Settings.Options.ScanClusteredIndex) it.Add((int)IndexType.CLUSTERED); + if (Settings.Settings.Options.ScanNonClusteredIndex) it.Add((int)IndexType.NONCLUSTERED); - if (Settings.ServerInfo.IsColumnstoreAvailable) { - if (Settings.Options.ScanClusteredColumnstore) it.Add((int)IndexType.CLUSTERED_COLUMNSTORE); - if (Settings.Options.ScanNonClusteredColumnstore) it.Add((int)IndexType.NONCLUSTERED_COLUMNSTORE); + if (Settings.Settings.ServerInfo.IsColumnstoreAvailable) { + if (Settings.Settings.Options.ScanClusteredColumnstore) it.Add((int)IndexType.CLUSTERED_COLUMNSTORE); + if (Settings.Settings.Options.ScanNonClusteredColumnstore) it.Add((int)IndexType.NONCLUSTERED_COLUMNSTORE); } - int threshold = Settings.Options.SkipOperation == IndexOp.IGNORE ? Settings.Options.FirstThreshold : 0; + int threshold = Settings.Settings.Options.SkipOperation == IndexOp.IGNORE ? Settings.Settings.Options.FirstThreshold : 0; List indexes = new List(); if (it.Count > 0) { string lob = string.Empty; - if (Settings.ServerInfo.IsOnlineRebuildAvailable) - lob = Settings.ServerInfo.MajorVersion == ServerVersion.Sql2008 ? Query.Lob2008 : Query.Lob2012Plus; + if (Settings.Settings.ServerInfo.IsOnlineRebuildAvailable) + lob = Settings.Settings.ServerInfo.MajorVersion == ServerVersion.Sql2008 ? Query.Lob2008 : Query.Lob2012Plus; - string indexStats = Settings.ServerInfo.IsAzure && connection.Database == Resources.DatamaseMaster + string indexStats = Settings.Settings.ServerInfo.IsAzure && connection.Database == MessageConstants.DatamaseMaster ? Query.IndexStatsAzureMaster : Query.IndexStats; - string indexQuery = Settings.ServerInfo.MajorVersion == ServerVersion.Sql2008 ? Query.Index2008 : Query.Index2012Plus; + string indexQuery = Settings.Settings.ServerInfo.MajorVersion == ServerVersion.Sql2008 ? Query.Index2008 : Query.Index2012Plus; - List excludeObjectMask = Settings.Options.ExcludeObject.Where(_ => _.Contains("%")).ToList(); - List includeObjectMask = Settings.Options.IncludeObject.Where(_ => _.Contains("%")).ToList(); - List excludeObjectId = Settings.Options.ExcludeObject.Where(_ => !_.Contains("%")).ToList(); - List includeObjectId = Settings.Options.IncludeObject.Where(_ => !_.Contains("%")).ToList(); + List excludeObjectMask = Settings.Settings.Options.ExcludeObject.Where(_ => _.Contains("%")).ToList(); + List includeObjectMask = Settings.Settings.Options.IncludeObject.Where(_ => _.Contains("%")).ToList(); + List excludeObjectId = Settings.Settings.Options.ExcludeObject.Where(_ => !_.Contains("%")).ToList(); + List includeObjectId = Settings.Settings.Options.IncludeObject.Where(_ => !_.Contains("%")).ToList(); string excludeList = string.Empty; - if (Settings.Options.ExcludeSchemas.Count > 0) - excludeList += "OR [schema_id] = SCHEMA_ID(N'" + string.Join("') OR [schema_id] = SCHEMA_ID(N'", Settings.Options.ExcludeSchemas) + "') "; + if (Settings.Settings.Options.ExcludeSchemas.Count > 0) + excludeList += "OR [schema_id] = SCHEMA_ID(N'" + string.Join("') OR [schema_id] = SCHEMA_ID(N'", Settings.Settings.Options.ExcludeSchemas) + "') "; if (excludeObjectMask.Count > 0) excludeList += "OR [name] LIKE N'" + string.Join("' OR [name] LIKE N'", excludeObjectMask) + "' "; @@ -138,8 +137,8 @@ public static List GetIndexes(SqlConnection connection) { if (excludeObjectId.Count > 0) excludeList += "OR [object_id] = OBJECT_ID(N'" + string.Join("') OR [object_id] = OBJECT_ID(N'", excludeObjectId) + "') "; - string includeListSchemas = Settings.Options.IncludeSchemas.Count > 0 - ? "AND ( [schema_id] = SCHEMA_ID(N'" + string.Join("') OR [schema_id] = SCHEMA_ID(N'", Settings.Options.IncludeSchemas) + "') ) " + string includeListSchemas = Settings.Settings.Options.IncludeSchemas.Count > 0 + ? "AND ( [schema_id] = SCHEMA_ID(N'" + string.Join("') OR [schema_id] = SCHEMA_ID(N'", Settings.Settings.Options.IncludeSchemas) + "') ) " : string.Empty; string includeListObject = string.Empty; @@ -152,29 +151,29 @@ public static List GetIndexes(SqlConnection connection) { if (!string.IsNullOrEmpty(includeListObject)) includeListObject = $"AND ( 1 = 0 {includeListObject})"; - int filterRows = Settings.Options.ShowOnlyMore1000Rows ? 1000 : 0; + int filterRows = Settings.Settings.Options.ShowOnlyMore1000Rows ? 1000 : 0; string includeList = string.IsNullOrEmpty(includeListSchemas) && string.IsNullOrEmpty(includeListObject) ? string.Format(Query.IncludeListEmpty, filterRows) : string.Format(Query.IncludeList, filterRows, includeListSchemas, includeListObject); - string ignoreReadOnlyFL = Settings.Options.IgnoreReadOnlyFL ? "" : "AND fg.[is_read_only] = 0 "; - string ignorePermissions = Settings.Options.IgnorePermissions ? "" : "AND PERMISSIONS(i.[object_id]) & 2 = 2 "; - string ignoreHeapWithCompression = Settings.Options.IgnoreHeapWithCompression ? "AND (i.[type] != 0 OR (i.[type] = 0 AND p.DataCompression = 0)) " : ""; + string ignoreReadOnlyFL = Settings.Settings.Options.IgnoreReadOnlyFL ? "" : "AND fg.[is_read_only] = 0 "; + string ignorePermissions = Settings.Settings.Options.IgnorePermissions ? "" : "AND PERMISSIONS(i.[object_id]) & 2 = 2 "; + string ignoreHeapWithCompression = Settings.Settings.Options.IgnoreHeapWithCompression ? "AND (i.[type] != 0 OR (i.[type] = 0 AND p.DataCompression = 0)) " : ""; - string statsInfo = Settings.ServerInfo.IsFullStats ? Query.StatsFull : Query.StatsLite; + string statsInfo = Settings.Settings.ServerInfo.IsFullStats ? Query.StatsFull : Query.StatsLite; string query = string.Format(Query.PreDescribeIndexes, string.Join(", ", it), excludeList, indexQuery, lob, indexStats, ignoreReadOnlyFL, ignorePermissions, includeList, ignoreHeapWithCompression, statsInfo); - SqlCommand cmd = new SqlCommand(query, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(query, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; cmd.Parameters.Add(new SqlParameter("@Fragmentation", SqlDbType.Float) { Value = threshold }); - cmd.Parameters.Add(new SqlParameter("@MinIndexSize", SqlDbType.BigInt) { Value = Settings.Options.MinIndexSize.PageSize() }); - cmd.Parameters.Add(new SqlParameter("@MaxIndexSize", SqlDbType.BigInt) { Value = Settings.Options.MaxIndexSize.PageSize() }); - cmd.Parameters.Add(new SqlParameter("@PreDescribeSize", SqlDbType.BigInt) { Value = Settings.Options.PreDescribeSize.PageSize() }); - cmd.Parameters.Add(new SqlParameter("@ScanMode", SqlDbType.NVarChar, 100) { Value = Settings.Options.ScanMode }); + cmd.Parameters.Add(new SqlParameter("@MinIndexSize", SqlDbType.BigInt) { Value = Settings.Settings.Options.MinIndexSize.PageSize() }); + cmd.Parameters.Add(new SqlParameter("@MaxIndexSize", SqlDbType.BigInt) { Value = Settings.Settings.Options.MaxIndexSize.PageSize() }); + cmd.Parameters.Add(new SqlParameter("@PreDescribeSize", SqlDbType.BigInt) { Value = Settings.Settings.Options.PreDescribeSize.PageSize() }); + cmd.Parameters.Add(new SqlParameter("@ScanMode", SqlDbType.NVarChar, 100) { Value = Settings.Settings.Options.ScanMode }); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); @@ -182,12 +181,12 @@ public static List GetIndexes(SqlConnection connection) { foreach (DataRow _ in data.Tables[0].AsEnumerable()) { - IndexType indexType = (IndexType)_.Field(Resources.IndexType); - bool isOnlineRebuild = Settings.ServerInfo.IsOnlineRebuildAvailable; + IndexType indexType = (IndexType)_.Field(MessageConstants.IndexType); + bool isOnlineRebuild = Settings.Settings.ServerInfo.IsOnlineRebuildAvailable; if (isOnlineRebuild) { if ( - _.Field(Resources.IsLobLegacy) + _.Field(MessageConstants.IsLobLegacy) || indexType == IndexType.CLUSTERED_COLUMNSTORE || @@ -197,106 +196,106 @@ public static List GetIndexes(SqlConnection connection) { } else { isOnlineRebuild = - Settings.ServerInfo.MajorVersion > ServerVersion.Sql2008 + Settings.Settings.ServerInfo.MajorVersion > ServerVersion.Sql2008 || - (Settings.ServerInfo.MajorVersion == ServerVersion.Sql2008 && !_.Field(Resources.IsLob)); + (Settings.Settings.ServerInfo.MajorVersion == ServerVersion.Sql2008 && !_.Field(MessageConstants.IsLob)); } } - DateTime? lastWrite = _.Field(Resources.LastWrite); - DateTime? lastRead = _.Field(Resources.LastRead); + DateTime? lastWrite = _.Field(MessageConstants.LastWrite); + DateTime? lastRead = _.Field(MessageConstants.LastRead); - Index index = new Index { + var index = new Index { DatabaseName = connection.Database, - ObjectId = _.Field(Resources.ObjectID), - IndexId = _.Field(Resources.IndexID), - IndexName = _.Field(Resources.IndexName), - ObjectName = _.Field(Resources.ObjectName), - SchemaName = _.Field(Resources.SchemaName), - PagesCount = _.Field(Resources.PagesCount), - UnusedPagesCount = _.Field(Resources.UnusedPagesCount), - PartitionNumber = _.Field(Resources.PartitionNumber), - RowsCount = _.Field(Resources.RowsCount), - FileGroupName = _.Field(Resources.FileGroupName), + ObjectId = _.Field(MessageConstants.ObjectID), + IndexId = _.Field(MessageConstants.IndexID), + IndexName = _.Field(MessageConstants.IndexName), + ObjectName = _.Field(MessageConstants.ObjectName), + SchemaName = _.Field(MessageConstants.SchemaName), + PagesCount = _.Field(MessageConstants.PagesCount), + UnusedPagesCount = _.Field(MessageConstants.UnusedPagesCount), + PartitionNumber = _.Field(MessageConstants.PartitionNumber), + RowsCount = _.Field(MessageConstants.RowsCount), + FileGroupName = _.Field(MessageConstants.FileGroupName), IndexType = indexType, - IsPartitioned = _.Field(Resources.IsPartitioned), - IsUnique = _.Field(Resources.IsUnique), - IsPK = _.Field(Resources.IsPK), - IsFiltered = _.Field(Resources.IsFiltered), - FillFactor = _.Field(Resources.FillFactor), - IndexStats = _.Field(Resources.IndexStats), - TotalUpdates = _.Field(Resources.TotalUpdates), - TotalSeeks = _.Field(Resources.TotalSeeks), - TotalScans = _.Field(Resources.TotalScans), - TotalLookups = _.Field(Resources.TotalLookups), + IsPartitioned = _.Field(MessageConstants.IsPartitioned), + IsUnique = _.Field(MessageConstants.IsUnique), + IsPK = _.Field(MessageConstants.IsPK), + IsFiltered = _.Field(MessageConstants.IsFiltered), + FillFactor = _.Field(MessageConstants.FillFactor), + IndexStats = _.Field(MessageConstants.IndexStats), + TotalUpdates = _.Field(MessageConstants.TotalUpdates), + TotalSeeks = _.Field(MessageConstants.TotalSeeks), + TotalScans = _.Field(MessageConstants.TotalScans), + TotalLookups = _.Field(MessageConstants.TotalLookups), LastWrite = lastWrite, LastRead = lastRead, LastUsage = Nullable.Compare(lastWrite, lastRead) > 0 ? lastWrite : lastRead, - CreateDate = _.Field(Resources.CreateDate), - ModifyDate = _.Field(Resources.ModifyDate), - DataCompression = (DataCompression)_.Field(Resources.DataCompression), - Fragmentation = _.Field(Resources.Fragmentation), - PageSpaceUsed = _.Field(Resources.PageSpaceUsed), - IsTable = _.Field(Resources.IsTable), - IsFKs = _.Field(Resources.IsFKs), - IsAllowReorganize = _.Field(Resources.IsAllowPageLocks) && indexType != IndexType.HEAP, + CreateDate = _.Field(MessageConstants.CreateDate), + ModifyDate = _.Field(MessageConstants.ModifyDate), + DataCompression = (DataCompression)_.Field(MessageConstants.DataCompression), + Fragmentation = _.Field(MessageConstants.Fragmentation), + PageSpaceUsed = _.Field(MessageConstants.PageSpaceUsed), + IsTable = _.Field(MessageConstants.IsTable), + IsFKs = _.Field(MessageConstants.IsFKs), + IsAllowReorganize = _.Field(MessageConstants.IsAllowPageLocks) && indexType != IndexType.HEAP, IsAllowOnlineRebuild = isOnlineRebuild, - IsAllowCompression = Settings.ServerInfo.IsCompressionAvailable && !_.Field(Resources.IsSparse), - IndexColumns = _.Field(Resources.IndexColumns), - IncludedColumns = _.Field(Resources.IncludedColumns), - IsNoRecompute = _.Field(Resources.IsNoRecompute), - StatsSampled = _.Field(Resources.StatsSampled), - RowsSampled = _.Field(Resources.RowsSampled) + IsAllowCompression = Settings.Settings.ServerInfo.IsCompressionAvailable && !_.Field(MessageConstants.IsSparse), + IndexColumns = _.Field(MessageConstants.IndexColumns), + IncludedColumns = _.Field(MessageConstants.IncludedColumns), + IsNoRecompute = _.Field(MessageConstants.IsNoRecompute), + StatsSampled = _.Field(MessageConstants.StatsSampled), + RowsSampled = _.Field(MessageConstants.RowsSampled) }; indexes.Add(index); } } - if (Settings.Options.ScanMissingIndex && !(Settings.ServerInfo.IsAzure && connection.Database == Resources.DatamaseMaster)) { + if (Settings.Settings.Options.ScanMissingIndex && !(Settings.Settings.ServerInfo.IsAzure && connection.Database == MessageConstants.DatamaseMaster)) { - SqlCommand cmd = new SqlCommand(Query.MissingIndex, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(Query.MissingIndex, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; cmd.Parameters.Add(new SqlParameter("@Fragmentation", SqlDbType.Float) { Value = threshold }); - cmd.Parameters.Add(new SqlParameter("@MinIndexSize", SqlDbType.BigInt) { Value = Settings.Options.MinIndexSize.PageSize() }); - cmd.Parameters.Add(new SqlParameter("@MaxIndexSize", SqlDbType.BigInt) { Value = Settings.Options.MaxIndexSize.PageSize() }); + cmd.Parameters.Add(new SqlParameter("@MinIndexSize", SqlDbType.BigInt) { Value = Settings.Settings.Options.MinIndexSize.PageSize() }); + cmd.Parameters.Add(new SqlParameter("@MaxIndexSize", SqlDbType.BigInt) { Value = Settings.Settings.Options.MaxIndexSize.PageSize() }); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); adapter.Fill(data); foreach (DataRow _ in data.Tables[0].AsEnumerable()) { - string indexCols = _.Field(Resources.IndexColumns); - string objName = _.Field(Resources.ObjectName); + string indexCols = _.Field(MessageConstants.IndexColumns); + string objName = _.Field(MessageConstants.ObjectName); string indexName = $"IX_{Guid.NewGuid().ToString().Truncate(5)}_{objName}_{indexCols}" .Replace(",", "_") .Replace("[", string.Empty) .Replace("]", string.Empty) .Replace(" ", string.Empty).Truncate(240); - DateTime? lastRead = _.Field(Resources.LastRead); + DateTime? lastRead = _.Field(MessageConstants.LastRead); Index index = new Index { DatabaseName = connection.Database, - ObjectId = _.Field(Resources.ObjectID), + ObjectId = _.Field(MessageConstants.ObjectID), IndexName = indexName, ObjectName = objName, - SchemaName = _.Field(Resources.SchemaName), - PagesCount = _.Field(Resources.PagesCount), - RowsCount = _.Field(Resources.RowsCount), + SchemaName = _.Field(MessageConstants.SchemaName), + PagesCount = _.Field(MessageConstants.PagesCount), + RowsCount = _.Field(MessageConstants.RowsCount), FileGroupName = "PRIMARY", IndexType = IndexType.MISSING_INDEX, - IndexStats = _.Field(Resources.IndexStats), - TotalSeeks = _.Field(Resources.TotalSeeks), - TotalScans = _.Field(Resources.TotalScans), + IndexStats = _.Field(MessageConstants.IndexStats), + TotalSeeks = _.Field(MessageConstants.TotalSeeks), + TotalScans = _.Field(MessageConstants.TotalScans), LastRead = lastRead, LastUsage = lastRead, DataCompression = DataCompression.NONE, - Fragmentation = _.Field(Resources.Fragmentation), + Fragmentation = _.Field(MessageConstants.Fragmentation), IsAllowOnlineRebuild = false, - IsAllowCompression = Settings.ServerInfo.IsCompressionAvailable, + IsAllowCompression = Settings.Settings.ServerInfo.IsCompressionAvailable, IndexColumns = indexCols, - IncludedColumns = _.Field(Resources.IncludedColumns) + IncludedColumns = _.Field(MessageConstants.IncludedColumns) }; indexes.Add(index); @@ -307,12 +306,12 @@ public static List GetIndexes(SqlConnection connection) { } public static void GetIndexFragmentation(SqlConnection connection, Index index) { - SqlCommand cmd = new SqlCommand(Query.IndexFragmentation, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(Query.IndexFragmentation, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; cmd.Parameters.Add(new SqlParameter("@ObjectID", SqlDbType.Int) { Value = index.ObjectId }); cmd.Parameters.Add(new SqlParameter("@IndexID", SqlDbType.Int) { Value = index.IndexId }); cmd.Parameters.Add(new SqlParameter("@PartitionNumber", SqlDbType.Int) { Value = index.PartitionNumber }); - cmd.Parameters.Add(new SqlParameter("@ScanMode", SqlDbType.NVarChar, 100) { Value = Settings.Options.ScanMode }); + cmd.Parameters.Add(new SqlParameter("@ScanMode", SqlDbType.NVarChar, 100) { Value = Settings.Settings.Options.ScanMode }); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); @@ -321,37 +320,37 @@ public static void GetIndexFragmentation(SqlConnection connection, Index index) if (data.Tables.Count == 1 && data.Tables[0].Rows.Count == 1) { DataRow row = data.Tables[0].Rows[0]; - index.Fragmentation = row.Field(Resources.Fragmentation); - index.PageSpaceUsed = row.Field(Resources.PageSpaceUsed); + index.Fragmentation = row.Field(MessageConstants.Fragmentation); + index.PageSpaceUsed = row.Field(MessageConstants.PageSpaceUsed); } } public static void GetColumnstoreFragmentation(SqlConnection connection, Index index, List indexes) { - SqlCommand cmd = new SqlCommand(Query.ColumnstoreIndexFragmentation, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(Query.ColumnstoreIndexFragmentation, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; - int threshold = Settings.Options.SkipOperation == IndexOp.IGNORE ? Settings.Options.FirstThreshold : 0; + int threshold = Settings.Settings.Options.SkipOperation == IndexOp.IGNORE ? Settings.Settings.Options.FirstThreshold : 0; cmd.Parameters.Add(new SqlParameter("@ObjectID", SqlDbType.Int) { Value = index.ObjectId }); cmd.Parameters.Add(new SqlParameter("@Fragmentation", SqlDbType.Float) { Value = threshold }); - cmd.Parameters.Add(new SqlParameter("@MinIndexSize", SqlDbType.BigInt) { Value = Settings.Options.MinIndexSize.PageSize() }); - cmd.Parameters.Add(new SqlParameter("@MaxIndexSize", SqlDbType.BigInt) { Value = Settings.Options.MaxIndexSize.PageSize() }); + cmd.Parameters.Add(new SqlParameter("@MinIndexSize", SqlDbType.BigInt) { Value = Settings.Settings.Options.MinIndexSize.PageSize() }); + cmd.Parameters.Add(new SqlParameter("@MaxIndexSize", SqlDbType.BigInt) { Value = Settings.Settings.Options.MaxIndexSize.PageSize() }); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); adapter.Fill(data); foreach(DataRow row in data.Tables[0].Rows) { - int indexId = row.Field(Resources.IndexID); - int partitionNumber = row.Field(Resources.PartitionNumber); + int indexId = row.Field(MessageConstants.IndexID); + int partitionNumber = row.Field(MessageConstants.PartitionNumber); Index idx = indexes.FirstOrDefault(_ => _.ObjectId == index.ObjectId && _.IndexId == indexId && _.PartitionNumber == partitionNumber); if (idx != null) { - idx.Fragmentation = row.Field(Resources.Fragmentation); - idx.PagesCount = row.Field(Resources.PagesCount); - idx.UnusedPagesCount = row.Field(Resources.UnusedPagesCount); + idx.Fragmentation = row.Field(MessageConstants.Fragmentation); + idx.PagesCount = row.Field(MessageConstants.PagesCount); + idx.UnusedPagesCount = row.Field(MessageConstants.UnusedPagesCount); } } } @@ -368,15 +367,15 @@ public static string FixIndex(SqlConnection connection, Index ix) { string sqlInfo; if (ix.IsColumnstore) sqlInfo = Query.AfterFixColumnstoreIndex; - else if (Settings.ServerInfo.IsFullStats && (ix.IndexType == IndexType.CLUSTERED || ix.IndexType == IndexType.NONCLUSTERED) && !ix.IsPartitioned) + else if (Settings.Settings.ServerInfo.IsFullStats && (ix.IndexType == IndexType.CLUSTERED || ix.IndexType == IndexType.NONCLUSTERED) && !ix.IsPartitioned) sqlInfo = Query.AfterFixIndexWithStats; else sqlInfo = Query.AfterFixIndex; - sql = $"{query} \n {string.Format(sqlInfo, ix.ObjectId, indexId, ix.PartitionNumber, Settings.Options.ScanMode)}"; + sql = $"{query} \n {string.Format(sqlInfo, ix.ObjectId, indexId, ix.PartitionNumber, Settings.Settings.Options.ScanMode)}"; } - SqlCommand cmd = new SqlCommand(sql, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(sql, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet data = new DataSet(); @@ -403,16 +402,16 @@ public static string FixIndex(SqlConnection connection, Index ix) { else if (data.Tables.Count == 1 && data.Tables[0].Rows.Count == 1) { DataRow row = data.Tables[0].Rows[0]; - ix.PagesCountBefore = ix.PagesCount - row.Field(Resources.PagesCount); - ix.Fragmentation = row.Field(Resources.Fragmentation); - ix.PageSpaceUsed = row.Field(Resources.PageSpaceUsed); - ix.PagesCount = row.Field(Resources.PagesCount); - ix.UnusedPagesCount = row.Field(Resources.UnusedPagesCount); - ix.RowsCount = row.Field(Resources.RowsCount); - ix.DataCompression = ((DataCompression)row.Field(Resources.DataCompression)); - ix.IndexStats = row.Field(Resources.IndexStats); - ix.StatsSampled = row.Field(Resources.StatsSampled) ?? ix.StatsSampled; - ix.RowsSampled = row.Field(Resources.RowsSampled) ?? ix.RowsSampled; + ix.PagesCountBefore = ix.PagesCount - row.Field(MessageConstants.PagesCount); + ix.Fragmentation = row.Field(MessageConstants.Fragmentation); + ix.PageSpaceUsed = row.Field(MessageConstants.PageSpaceUsed); + ix.PagesCount = row.Field(MessageConstants.PagesCount); + ix.UnusedPagesCount = row.Field(MessageConstants.UnusedPagesCount); + ix.RowsCount = row.Field(MessageConstants.RowsCount); + ix.DataCompression = ((DataCompression)row.Field(MessageConstants.DataCompression)); + ix.IndexStats = row.Field(MessageConstants.IndexStats); + ix.StatsSampled = row.Field(MessageConstants.StatsSampled) ?? ix.StatsSampled; + ix.RowsSampled = row.Field(MessageConstants.RowsSampled) ?? ix.RowsSampled; if (ix.FixType == IndexOp.CREATE_COLUMNSTORE_INDEX) { ix.IndexName = "CCL"; @@ -479,13 +478,13 @@ private static IndexOp CorrectIndexOp(IndexOp op, Index ix) { return IndexOp.REORGANIZE; if (op == IndexOp.REBUILD && !ix.IsColumnstore && ix.IsAllowCompression) { - if (Settings.Options.DataCompression == DataCompression.NONE && ix.DataCompression != DataCompression.NONE) + if (Settings.Settings.Options.DataCompression == DataCompression.NONE && ix.DataCompression != DataCompression.NONE) return IndexOp.REBUILD_NONE; - if (Settings.Options.DataCompression == DataCompression.ROW && ix.DataCompression != DataCompression.ROW) + if (Settings.Settings.Options.DataCompression == DataCompression.ROW && ix.DataCompression != DataCompression.ROW) return IndexOp.REBUILD_ROW; - if (Settings.Options.DataCompression == DataCompression.PAGE && ix.DataCompression != DataCompression.PAGE) + if (Settings.Settings.Options.DataCompression == DataCompression.PAGE && ix.DataCompression != DataCompression.PAGE) return IndexOp.REBUILD_PAGE; } @@ -495,32 +494,32 @@ private static IndexOp CorrectIndexOp(IndexOp op, Index ix) { } } - return Settings.Options.Online && ix.IsAllowOnlineRebuild && (op == IndexOp.REBUILD || op == IndexOp.REORGANIZE) + return Settings.Settings.Options.Online && ix.IsAllowOnlineRebuild && (op == IndexOp.REBUILD || op == IndexOp.REORGANIZE) ? IndexOp.REBUILD_ONLINE : IndexOp.REBUILD; } public static void UpdateFixType(List indexes) { foreach (Index ix in indexes) { - if (ix.Fragmentation < Settings.Options.FirstThreshold) { - ix.FixType = CorrectIndexOp(Settings.Options.SkipOperation, ix); + if (ix.Fragmentation < Settings.Settings.Options.FirstThreshold) { + ix.FixType = CorrectIndexOp(Settings.Settings.Options.SkipOperation, ix); } - else if (ix.Fragmentation < Settings.Options.SecondThreshold) { - ix.FixType = CorrectIndexOp(Settings.Options.FirstOperation, ix); + else if (ix.Fragmentation < Settings.Settings.Options.SecondThreshold) { + ix.FixType = CorrectIndexOp(Settings.Settings.Options.FirstOperation, ix); } else { - ix.FixType = CorrectIndexOp(Settings.Options.SecondOperation, ix); + ix.FixType = CorrectIndexOp(Settings.Settings.Options.SecondOperation, ix); } } } public static void KillActiveSessions() { - if (!Settings.ServerInfo.IsSysAdmin) return; + if (!Settings.Settings.ServerInfo.IsSysAdmin) return; - using (SqlConnection connection = Connection.Create(Settings.ActiveHost)) { + using (SqlConnection connection = ConnectionUtils.Create(Settings.Settings.ActiveHost)) { try { connection.Open(); - SqlCommand cmd = new SqlCommand(Query.KillActiveSessions, connection) { CommandTimeout = Settings.Options.CommandTimeout }; + SqlCommand cmd = new SqlCommand(Query.KillActiveSessions, connection) { CommandTimeout = Settings.Settings.Options.CommandTimeout }; cmd.Parameters.Add(new SqlParameter("@ApplicationName", SqlDbType.NVarChar, 128) { Value = AppInfo.ApplicationName }); cmd.ExecuteNonQuery(); } diff --git a/Types/ScanMode.cs b/SQLIndexManager.Core/Server/ScanMode.cs similarity index 66% rename from Types/ScanMode.cs rename to SQLIndexManager.Core/Server/ScanMode.cs index 1a55b2b..bed3704 100644 --- a/Types/ScanMode.cs +++ b/SQLIndexManager.Core/Server/ScanMode.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum ScanMode { LIMITED = 0, diff --git a/Server/ServerInfo.cs b/SQLIndexManager.Core/Server/ServerInfo.cs similarity index 98% rename from Server/ServerInfo.cs rename to SQLIndexManager.Core/Server/ServerInfo.cs index 2918d0f..2d4756c 100644 --- a/Server/ServerInfo.cs +++ b/SQLIndexManager.Core/Server/ServerInfo.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public class ServerInfo { public readonly string ServerName; diff --git a/Types/ServerVersion.cs b/SQLIndexManager.Core/Server/ServerVersion.cs similarity index 88% rename from Types/ServerVersion.cs rename to SQLIndexManager.Core/Server/ServerVersion.cs index 52d92a0..e3ae7c0 100644 --- a/Types/ServerVersion.cs +++ b/SQLIndexManager.Core/Server/ServerVersion.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public static class ServerVersion { public const int Sql2005 = 9; diff --git a/Types/WarningType.cs b/SQLIndexManager.Core/Server/WarningType.cs similarity index 66% rename from Types/WarningType.cs rename to SQLIndexManager.Core/Server/WarningType.cs index f29bb5b..6641b87 100644 --- a/Types/WarningType.cs +++ b/SQLIndexManager.Core/Server/WarningType.cs @@ -1,4 +1,4 @@ -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Server { public enum WarningType { UNUSED = 1, diff --git a/Settings/GlobalSettings.cs b/SQLIndexManager.Core/Settings/GlobalSettings.cs similarity index 77% rename from Settings/GlobalSettings.cs rename to SQLIndexManager.Core/Settings/GlobalSettings.cs index fb991f0..8958d70 100644 --- a/Settings/GlobalSettings.cs +++ b/SQLIndexManager.Core/Settings/GlobalSettings.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; using System.Xml.Serialization; +using SQLIndexManager.Core.Server; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Settings { [Serializable] public class GlobalSettings { diff --git a/Settings/Options.cs b/SQLIndexManager.Core/Settings/Options.cs similarity index 99% rename from Settings/Options.cs rename to SQLIndexManager.Core/Settings/Options.cs index 6baceac..8e3723c 100644 --- a/Settings/Options.cs +++ b/SQLIndexManager.Core/Settings/Options.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; using System.Xml.Serialization; +using SQLIndexManager.Core.Server; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Settings { [Serializable] public class Options { diff --git a/Settings/Settings.cs b/SQLIndexManager.Core/Settings/Settings.cs similarity index 92% rename from Settings/Settings.cs rename to SQLIndexManager.Core/Settings/Settings.cs index e20d257..7b1518d 100644 --- a/Settings/Settings.cs +++ b/SQLIndexManager.Core/Settings/Settings.cs @@ -4,10 +4,11 @@ using System.Linq; using System.Xml.Serialization; using Microsoft.Win32; +using SQLIndexManager.Core.Server; -namespace SQLIndexManager { +namespace SQLIndexManager.Core.Settings { - public class Settings { + public static class Settings { private static GlobalSettings _current; private static Host _activeHost; @@ -111,6 +112,18 @@ private static void Load() { } } + try { + LoadFromRegistry(); + } + catch (PlatformNotSupportedException ex) { + Output.Current.Add("Registry is not supported on this platform."); + } + + if (_current.Hosts.Count == 0) { + _current.Hosts.Add(new Host() { Server = Environment.MachineName }); + } + } + private static void LoadFromRegistry() { RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32; using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView)) { RegistryKey instanceKey = null; @@ -120,7 +133,7 @@ private static void Load() { catch { Output.Current.Add("Failed to read registry"); } - + if (instanceKey != null) { foreach (string instanceName in instanceKey.GetValueNames()) { string host = (instanceName == "MSSQLSERVER") ? Environment.MachineName : $"{Environment.MachineName}\\{instanceName}"; @@ -130,10 +143,6 @@ private static void Load() { } } } - - if (_current.Hosts.Count == 0) { - _current.Hosts.Add(new Host() { Server = Environment.MachineName }); - } } } diff --git a/Common/Utils.cs b/SQLIndexManager.Core/Utils.cs similarity index 92% rename from Common/Utils.cs rename to SQLIndexManager.Core/Utils.cs index 6b177b6..ca92522 100644 --- a/Common/Utils.cs +++ b/SQLIndexManager.Core/Utils.cs @@ -3,17 +3,10 @@ using System.ComponentModel; using System.Linq; -namespace SQLIndexManager { +namespace SQLIndexManager.Core { public static class Utils { - public static void ShowErrorFrom(Exception e, string message = "Error") { - Output.Current.Add($"{message}: {e.Source}", e.Message); - using (ErrorBox errorBox = new ErrorBox(e)) { - errorBox.ShowDialog(); - } - } - public static string Description(this Enum value) { var da = (DescriptionAttribute[])(value.GetType().GetField(value.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false); return da.Length > 0 ? da[0].Description : value.ToString(); diff --git a/SQLIndexManager.csproj b/SQLIndexManager.csproj index e07f94a..abc2deb 100644 --- a/SQLIndexManager.csproj +++ b/SQLIndexManager.csproj @@ -79,18 +79,14 @@ - - Component - + Component - - - + Form @@ -116,27 +112,13 @@ SplashScreenBox.cs + True True Resources.resx - - - - - - - - - - - - - - - Form @@ -156,14 +138,6 @@ ConnectionBox.cs - - - - - - - - ErrorBox.cs @@ -228,6 +202,15 @@ + + + {96c94bac-f145-4b7a-ac4e-40c1dca8b729} + SQLIndexManager.Core + + + + +