示例#1
0
        private static string FormatSql(string sql)
        {
            Console.WriteLine($"[Formatting] resulting SQL code.");
            var options = new TSqlStandardFormatterOptions
            {
                KeywordStandardization   = true,
                IndentString             = "\t",
                SpacesPerTab             = 4,
                MaxLineWidth             = 999,
                NewStatementLineBreaks   = 2,
                NewClauseLineBreaks      = 1,
                TrailingCommas           = false,
                SpaceAfterExpandedComma  = false,
                ExpandBetweenConditions  = true,
                ExpandBooleanExpressions = true,
                ExpandCaseStatements     = true,
                ExpandCommaLists         = true,
                BreakJoinOnSections      = true,
                UppercaseKeywords        = true,
                ExpandInLists            = true
            };

            var parsingError      = false;
            var formatter         = new TSqlStandardFormatter(options);
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);
            var formattedOutput   = formattingManager.Format(sql, ref parsingError);

            return(formattedOutput);
        }
示例#2
0
        public string FormatTSqlToString(string inputString)
        {
            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
            {
                KeywordStandardization   = true,
                IndentString             = "\t",
                SpacesPerTab             = 4,
                MaxLineWidth             = 999,
                NewStatementLineBreaks   = 1,
                NewClauseLineBreaks      = 1,
                TrailingCommas           = false,
                SpaceAfterExpandedComma  = false,
                ExpandBetweenConditions  = true,
                ExpandBooleanExpressions = true,
                ExpandCaseStatements     = true,
                ExpandCommaLists         = true,
                BreakJoinOnSections      = false,
                UppercaseKeywords        = true,
                ExpandInLists            = true
            };

            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter _formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(options);
            var  formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(_formatter);
            bool parsingError      = false;

            return(formattingManager.Format(inputString, ref parsingError));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PoorMansTSqlFormatterCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private PoorMansTSqlFormatterCommand(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            this.package = package;

            OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (commandService != null)
            {
                _applicationObject = Package.GetGlobalService(typeof(DTE)) as DTE;
                _formattingManager = PoorMansTSqlFormatterPluginShared.Utils.GetFormattingManager(Properties.Settings.Default);
                //Command cmd = _applicationObject.Commands.Item("Tools.FormatTSQLCode", -1);
                //cmd.Bindings = "Text Editor::Ctrl+Shift+D";

                var menuFormatCommandID = new CommandID(CommandSet, FormatCommandId);
                var menuFormatItem = new MenuCommand(this.MenuFormatCallback, menuFormatCommandID);
                commandService.AddCommand(menuFormatItem);

                var menuOptionsCommandID = new CommandID(CommandSet, OptionsCommandId);
                var menuOptionsItem = new MenuCommand(this.MenuOptionsCallback, menuOptionsCommandID);
                commandService.AddCommand(menuOptionsItem);

                _formatCommand = _applicationObject.Commands.Item("Tools.FormatTSQLCode", -1);
                SetFormatHotkey();

            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PoorMansTSqlFormatterCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private PoorMansTSqlFormatterCommand(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            this.package = package;

            OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (commandService != null)
            {
                _applicationObject = Package.GetGlobalService(typeof(DTE)) as DTE;
                _formattingManager = PoorMansTSqlFormatterPluginShared.Utils.GetFormattingManager(Properties.Settings.Default);
                //Command cmd = _applicationObject.Commands.Item("Tools.FormatTSQLCode", -1);
                //cmd.Bindings = "Text Editor::Ctrl+Shift+D";

                var menuFormatCommandID = new CommandID(CommandSet, FormatCommandId);
                var menuFormatItem      = new MenuCommand(this.MenuFormatCallback, menuFormatCommandID);
                commandService.AddCommand(menuFormatItem);

                var menuOptionsCommandID = new CommandID(CommandSet, OptionsCommandId);
                var menuOptionsItem      = new MenuCommand(this.MenuOptionsCallback, menuOptionsCommandID);
                commandService.AddCommand(menuOptionsItem);

                _formatCommand = _applicationObject.Commands.Item("Tools.FormatTSQLCode", -1);
                SetFormatHotkey();
            }
        }
示例#5
0
        internal static void CommandMenuInit()
        {
            //this is where I'd really like access to language info from Notepad++ context...
            //MessageBox.Show(string.Format("Cult: {0}; UICult: {1}", System.Threading.Thread.CurrentThread.CurrentCulture.EnglishName, System.Threading.Thread.CurrentThread.CurrentUICulture.EnglishName));

            //get settings from notepad++-assigned plugin data folder, and set for settings provider.
            StringBuilder sbIniFilePath = new StringBuilder(Win32.MAX_PATH);

            Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETPLUGINSCONFIGDIR, Win32.MAX_PATH, sbIniFilePath);
            string iniFolder = sbIniFilePath.ToString();

            if (!Directory.Exists(iniFolder))
            {
                Directory.CreateDirectory(iniFolder);
            }
            iniFilePath = Path.Combine(iniFolder, PluginName + ".ini.xml");
            Properties.Settings.Default.Context["settingsPath"] = iniFilePath;

            _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);

            //set up menu items
            PluginBase.SetCommand(0, _generalResourceManager.GetString("FormatButtonText"), formatSqlCommand, new ShortcutKey(false, false, false, Keys.None));
            // disable option dialog as we want everyone using the same options
            //PluginBase.SetCommand(1, _generalResourceManager.GetString("OptionsButtonText"), formattingOptionsCommand, new ShortcutKey(false, false, false, Keys.None));
        }
示例#6
0
        internal static void formattingOptionsCommand()
        {
            SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"));

            if (settings.ShowDialog() == DialogResult.OK)
            {
                _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
            }
            settings.Dispose();
        }
        private void MenuOptionsCallback(object sender, EventArgs e)
        {
            GetFormatHotkey();
            SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));

            if (settings.ShowDialog() == DialogResult.OK)
            {
                SetFormatHotkey();
                _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
            }
        }
        /// <summary>Constructor - non-environment-related initialization here.</summary>
		public AddinConnector()
		{
            //upgrade settings if necessary.
            if (!Properties.Settings.Default.UpgradeCompleted)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpgradeCompleted = true;
                Properties.Settings.Default.Save();
            }

            //set up formatter (note - after changes to Settings through the UI this line will appear to error, 
            // with settings not implementing the necessary interface, but a prebuild search & replace step will 
            // automatically fix the settings file)
            _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
		}
        /// <summary>Constructor - non-environment-related initialization here.</summary>
        public AddinConnector()
        {
            //upgrade settings if necessary.
            if (!Properties.Settings.Default.UpgradeCompleted)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpgradeCompleted = true;
                Properties.Settings.Default.Save();
            }

            //set up formatter (note - after changes to Settings through the UI this line will appear to error,
            // with settings not implementing the necessary interface, but a prebuild search & replace step will
            // automatically fix the settings file)
            _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
        }
示例#10
0
        /// <summary>
        /// Format a SQL string.
        /// </summary>
        /// <param name="originalString">The original SQL string.</param>
        /// <returns>Returns a formatted SQL string according to the properties which have been set up for this class.</returns>
        public string FormatString(string originalString)
        {
            var formatOptions = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions()
            {
                TrailingCommas      = true,
                BreakJoinOnSections = true,
                IndentString        = this.IndentationString,
                UppercaseKeywords   = true,
                SpacesPerTab        = 2,
            };

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(formatOptions);

            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            return(formattingManager.Format(originalString));
        }
示例#11
0
        internal static void CommandMenuInit()
        {
            //this is where I'd really like access to language info from Notepad++ context...
            //MessageBox.Show(string.Format("Cult: {0}; UICult: {1}", System.Threading.Thread.CurrentThread.CurrentCulture.EnglishName, System.Threading.Thread.CurrentThread.CurrentUICulture.EnglishName));

            //get settings from notepad++-assigned plugin data folder, and set for settings provider.
            StringBuilder sbIniFilePath = new StringBuilder(Win32.MAX_PATH);
            Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETPLUGINSCONFIGDIR, Win32.MAX_PATH, sbIniFilePath);
            string iniFolder = sbIniFilePath.ToString();
            if (!Directory.Exists(iniFolder)) Directory.CreateDirectory(iniFolder);
            iniFilePath = Path.Combine(iniFolder, PluginName + ".ini.xml");
            Properties.Settings.Default.Context["settingsPath"] = iniFilePath;

            _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);

            //set up menu items
            PluginBase.SetCommand(0, _generalResourceManager.GetString("FormatButtonText"), formatSqlCommand, new ShortcutKey(false, false, false, Keys.None));
            PluginBase.SetCommand(1, _generalResourceManager.GetString("OptionsButtonText"), formattingOptionsCommand, new ShortcutKey(false, false, false, Keys.None));
        }
示例#12
0
        /// <summary>
        /// Format a SQL string.
        /// </summary>
        /// <param name="originalString">The original SQL string.</param>
        /// <returns>Returns a formatted SQL string according to the properties which have been set up for this class.</returns>
        public string FormatString(string originalString)
        {
            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                indentString: this.IndentationString,
                spacesPerTab: 2,
                maxLineWidth: 999,
                expandCommaLists: true,
                trailingCommas: false,
                spaceAfterExpandedComma: false,
                expandBooleanExpressions: true,
                expandCaseStatements: true,
                expandBetweenConditions: true,
                breakJoinOnSections: true,
                uppercaseKeywords: true,
                htmlColoring: false,
                keywordStandardization: false);

            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            return(formattingManager.Format(originalString));
        }
示例#13
0
        /// <summary>
        /// Format a SQL statement
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>

        public static string FormatSql(string sql)
        {
            bool errorEncountered = false;

            if (Lex.IsUndefined(sql))
            {
                return("");
            }

            PoorMansTSqlFormatterLib.SqlFormattingManager mgr = new PoorMansTSqlFormatterLib.SqlFormattingManager();

            PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter fmtr = mgr.Formatter as PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter;
            if (fmtr != null)
            {
                fmtr.Options.TrailingCommas = true;
            }

            string formattedSql = mgr.Format(sql, ref errorEncountered);

            formattedSql = Lex.Replace(formattedSql, "--WARNING! ERRORS ENCOUNTERED DURING SQL PARSING!\r\n", "");
            return(formattedSql);
        }
示例#14
0
        private string FormatTSqlWithFormatter(string inputString, PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter formatter)
        {
            //free use is all very nice, but I REALLY don't want anyone linking to this web service from some
            // other site or app: they should just download the library and incorporate or host it directly.
            // (assuming the project is GPL-compatible)
            //
            string allowedHost = System.Configuration.ConfigurationSettings.AppSettings["ReferrerHostValidation"];

            //no error handling, just do the bare (safe) minimum.
            if (string.IsNullOrEmpty(allowedHost) ||
                (Context.Request.UrlReferrer != null &&
                 Context.Request.UrlReferrer.Host != null &&
                 Context.Request.UrlReferrer.Host.Equals(allowedHost)
                )
                )
            {
                PoorMansTSqlFormatterLib.SqlFormattingManager fullFormatter = new PoorMansTSqlFormatterLib.SqlFormattingManager(new PoorMansTSqlFormatterLib.Formatters.HtmlPageWrapper(formatter));
                return(fullFormatter.Format(inputString));
            }
            else
            {
                return(string.Format("Sorry, this web service can only be called from code hosted at {0}.", allowedHost));
            }
        }
示例#15
0
        static int Main(string[] args)
        {
            string indentString             = "\t";
            int    spacesPerTab             = 4;
            int    maxLineWidth             = 999;
            bool   trailingCommas           = false;
            bool   spaceAfterExpandedComma  = false;
            bool   expandBetweenConditions  = true;
            bool   expandBooleanExpressions = true;
            bool   expandCaseStatements     = true;
            bool   expandCommaLists         = true;
            bool   breakJoinOnSections      = false;
            bool   uppercaseKeywords        = true;
            bool   standardizeKeywords      = true;

            bool          allowParsingErrors = false;
            bool          showUsageFriendly  = false;
            bool          showUsageError     = false;
            List <string> extensions         = new List <string>();
            bool          backups            = true;
            bool          recursiveSearch    = false;
            string        outputFileOrFolder = null;
            string        uiLangCode         = null;

            OptionSet p = new OptionSet()
                          .Add("is|indentString=", delegate(string v) { indentString = v; })
                          .Add("st|spacesPerTab=", delegate(string v) { spacesPerTab = int.Parse(v); })
                          .Add("mw|maxLineWidth=", delegate(string v) { maxLineWidth = int.Parse(v); })
                          .Add("tc|trailingCommas", delegate(string v) { trailingCommas = v != null; })
                          .Add("sac|spaceAfterExpandedComma", delegate(string v) { spaceAfterExpandedComma = v != null; })
                          .Add("ebc|expandBetweenConditions", delegate(string v) { expandBetweenConditions = v != null; })
                          .Add("ebe|expandBooleanExpressions", delegate(string v) { expandBooleanExpressions = v != null; })
                          .Add("ecs|expandCaseStatements", delegate(string v) { expandCaseStatements = v != null; })
                          .Add("ecl|expandCommaLists", delegate(string v) { expandCommaLists = v != null; })
                          .Add("bjo|breakJoinOnSections", delegate(string v) { breakJoinOnSections = v != null; })
                          .Add("uk|uppercaseKeywords", delegate(string v) { uppercaseKeywords = v != null; })
                          .Add("sk|standardizeKeywords", delegate(string v) { standardizeKeywords = v != null; })
                          .Add("ae|allowParsingErrors", delegate(string v) { allowParsingErrors = v != null; })
                          .Add("e|extensions=", delegate(string v) { extensions.Add((v.StartsWith(".") ? "" : ".") + v); })
                          .Add("r|recursive", delegate(string v) { recursiveSearch = v != null; })
                          .Add("b|backups", delegate(string v) { backups = v != null; })
                          .Add("o|outputFileOrFolder=", delegate(string v) { outputFileOrFolder = v; })
                          .Add("l|languageCode=", delegate(string v) { uiLangCode = v; })
                          .Add("h|?|help", delegate(string v) { showUsageFriendly = v != null; })
            ;

            //first parse the args
            List <string> remainingArgs = p.Parse(args);

            //then switch language if necessary
            if (uiLangCode != null)
            {
                uiLangCode = uiLangCode.ToUpperInvariant();
                if (!uiLangCode.Equals(UILANGUAGE_EN) &&
                    !uiLangCode.Equals(UILANGUAGE_FR) &&
                    !uiLangCode.Equals(UILANGUAGE_ES)
                    )
                {
                    showUsageError = true;
                    //get the resource manager with default language, before displaying error.
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedLanguageErrorMessage"));
                }
                else
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(uiLangCode);
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    //get the resource manager AFTER setting language as requested.
                }
            }
            else
            {
                _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
            }

            //nasty trick to figure out whether we're in a pipeline or not
            bool   throwAwayValue;
            string stdInput = null;

            try
            {
                throwAwayValue = System.Console.KeyAvailable;
            }
            catch (InvalidOperationException)
            {
                Console.InputEncoding = Encoding.UTF8;
                stdInput = System.Console.In.ReadToEnd();
            }

            //then complain about missing input or unrecognized args
            if (string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 0)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("NoInputErrorMessage"));
            }
            else if ((!string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 1) || remainingArgs.Count > 1)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedArgumentsErrorMessage"));
            }

            if (extensions.Count == 0)
            {
                extensions.Add(".sql");
            }

            if (showUsageFriendly || showUsageError)
            {
                TextWriter outStream = showUsageFriendly ? Console.Out : Console.Error;
                outStream.WriteLine(_generalResourceManager.GetString("ProgramSummary"));
                outStream.WriteLine("v" + Assembly.GetExecutingAssembly().GetName().Version.ToString());
                outStream.WriteLine(_generalResourceManager.GetString("ProgramUsageNotes"));
                return(1);
            }

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                indentString,
                spacesPerTab,
                maxLineWidth,
                expandCommaLists,
                trailingCommas,
                spaceAfterExpandedComma,
                expandBooleanExpressions,
                expandCaseStatements,
                expandBetweenConditions,
                breakJoinOnSections,
                uppercaseKeywords,
                false,
                standardizeKeywords
                );

            formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            bool warningEncountered = false;

            if (!string.IsNullOrEmpty(stdInput))
            {
                string    formattedOutput = null;
                bool      parsingError    = false;
                Exception parseException  = null;
                try
                {
                    formattedOutput = formattingManager.Format(stdInput, ref parsingError);

                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors)
                    {
                        parsingError = false;
                    }
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError   = true;
                }

                if (parsingError)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ParsingErrorWarningMessage"), "STDIN"));
                    if (parseException != null)
                    {
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), parseException.Message));
                    }
                    warningEncountered = true;
                }
                else
                {
                    if (!string.IsNullOrEmpty(outputFileOrFolder))
                    {
                        WriteResultFile(outputFileOrFolder, null, null, ref warningEncountered, formattedOutput);
                    }
                    else
                    {
                        Console.OutputEncoding = Encoding.UTF8;
                        Console.Out.WriteLine(formattedOutput);
                    }
                }
            }
            else
            {
                System.IO.DirectoryInfo baseDirectory = null;
                string searchPattern     = Path.GetFileName(remainingArgs[0]);
                string baseDirectoryName = Path.GetDirectoryName(remainingArgs[0]);
                if (baseDirectoryName.Length == 0)
                {
                    baseDirectoryName = ".";
                    if (searchPattern.Equals("."))
                    {
                        searchPattern = "";
                    }
                }
                System.IO.FileSystemInfo[] matchingObjects = null;
                try
                {
                    baseDirectory = new System.IO.DirectoryInfo(baseDirectoryName);
                    if (searchPattern.Length > 0)
                    {
                        if (recursiveSearch)
                        {
                            matchingObjects = baseDirectory.GetFileSystemInfos(searchPattern);
                        }
                        else
                        {
                            matchingObjects = baseDirectory.GetFiles(searchPattern);
                        }
                    }
                    else
                    {
                        if (recursiveSearch)
                        {
                            matchingObjects = baseDirectory.GetFileSystemInfos();
                        }
                        else
                        {
                            matchingObjects = new FileSystemInfo[0];
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("PathPatternErrorMessage"), e.Message));
                    return(2);
                }

                System.IO.StreamWriter singleFileWriter = null;
                string replaceFromFolderPath            = null;
                string replaceToFolderPath = null;
                if (!string.IsNullOrEmpty(outputFileOrFolder))
                {
                    //ignore the backups setting - wouldn't make sense to back up the source files if we're
                    // writing to another file anyway...
                    backups = false;

                    if (Directory.Exists(outputFileOrFolder) &&
                        (File.GetAttributes(outputFileOrFolder) & FileAttributes.Directory) == FileAttributes.Directory
                        )
                    {
                        replaceFromFolderPath = baseDirectory.FullName;
                        replaceToFolderPath   = new DirectoryInfo(outputFileOrFolder).FullName;
                    }
                    else
                    {
                        try
                        {
                            //let's not worry too hard about releasing this resource - this is a command-line program,
                            // when it ends or dies all will be released anyway.
                            singleFileWriter = new StreamWriter(outputFileOrFolder);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("OutputFileCreationErrorMessage"), e.Message));
                            return(3);
                        }
                    }
                }

                if (!ProcessSearchResults(extensions, backups, allowParsingErrors, formattingManager, matchingObjects, singleFileWriter, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered))
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("NoFilesFoundWarningMessage"), remainingArgs[0], string.Join(",", extensions.ToArray())));
                    return(4);
                }

                if (singleFileWriter != null)
                {
                    singleFileWriter.Flush();
                    singleFileWriter.Close();
                    singleFileWriter.Dispose();
                }
            }

            if (warningEncountered)
            {
                return(5); //general "there were warnings" return code
            }
            else
            {
                return(0); //we got there, did something, and received no (handled) errors!
            }
        }
示例#16
0
 internal static void formattingOptionsCommand()
 {
     SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"));
     if (settings.ShowDialog() == DialogResult.OK)
     {
         _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
     }
     settings.Dispose();
 }
示例#17
0
        private static bool ProcessSearchResults(List <string> extensions, bool backups, bool allowParsingErrors, PoorMansTSqlFormatterLib.SqlFormattingManager formattingManager, FileSystemInfo[] matchingObjects, StreamWriter singleFileWriter, string replaceFromFolderPath, string replaceToFolderPath, ref bool warningEncountered)
        {
            bool fileFound = false;

            foreach (var fsEntry in matchingObjects)
            {
                if (fsEntry is FileInfo)
                {
                    if (extensions.Contains(fsEntry.Extension))
                    {
                        ReFormatFile((FileInfo)fsEntry, formattingManager, backups, allowParsingErrors, singleFileWriter, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered);
                        fileFound = true;
                    }
                }
                else
                {
                    if (ProcessSearchResults(extensions, backups, allowParsingErrors, formattingManager, ((System.IO.DirectoryInfo)fsEntry).GetFileSystemInfos(), singleFileWriter, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered))
                    {
                        fileFound = true;
                    }
                }
            }

            return(fileFound);
        }
示例#18
0
        private static void ReFormatFile(FileInfo fileInfo, PoorMansTSqlFormatterLib.SqlFormattingManager formattingManager, bool backups, bool allowParsingErrors, StreamWriter singleFileWriter, string replaceFromFolderPath, string replaceToFolderPath, ref bool warningEncountered)
        {
            bool      failedBackup    = false;
            string    oldFileContents = "";
            string    newFileContents = "";
            bool      parsingError    = false;
            bool      failedFolder    = false;
            Exception parseException  = null;

            //TODO: play with / test encoding complexities
            //TODO: consider using auto-detection - read binary, autodetect, convert.
            //TODO: consider whether to keep same output encoding as source file, or always use same, and if so whether to make parameter-based.
            try
            {
                oldFileContents = System.IO.File.ReadAllText(fileInfo.FullName);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("FileReadFailureWarningMessage"), fileInfo.FullName));
                Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), ex.Message));
                warningEncountered = true;
            }
            if (oldFileContents.Length > 0)
            {
                try
                {
                    newFileContents = formattingManager.Format(oldFileContents, ref parsingError);

                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors)
                    {
                        parsingError = false;
                    }
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError   = true;
                }

                if (parsingError)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ParsingErrorWarningMessage"), fileInfo.FullName));
                    if (parseException != null)
                    {
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), parseException.Message));
                    }
                    warningEncountered = true;
                }
            }
            if (!parsingError &&
                (
                    (newFileContents.Length > 0 &&
                     !oldFileContents.Equals(newFileContents)
                    ) ||
                    singleFileWriter != null ||
                    (replaceFromFolderPath != null && replaceToFolderPath != null)
                )
                )

            {
                if (backups)
                {
                    try
                    {
                        fileInfo.CopyTo(fileInfo.FullName + ".bak", true);
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("BackupFailureWarningMessage"), fileInfo.FullName, Environment.NewLine));
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), ex.Message));
                        failedBackup       = true;
                        warningEncountered = true;
                    }
                }
                if (!failedBackup)
                {
                    if (singleFileWriter != null)
                    {
                        //we'll assume that running out of disk space, and other while-you-are-writing errors, and not worth worrying about
                        singleFileWriter.WriteLine(newFileContents);
                        singleFileWriter.WriteLine("GO");
                    }
                    else
                    {
                        string fullTargetPath = fileInfo.FullName;
                        if (replaceFromFolderPath != null && replaceToFolderPath != null)
                        {
                            fullTargetPath = fullTargetPath.Replace(replaceFromFolderPath, replaceToFolderPath);

                            string targetFolder = Path.GetDirectoryName(fullTargetPath);
                            try
                            {
                                if (!Directory.Exists(targetFolder))
                                {
                                    Directory.CreateDirectory(targetFolder);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("FolderCreationFailureWarningMessage"), targetFolder));
                                Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), ex.Message));
                                failedFolder       = true;
                                warningEncountered = true;
                            }
                        }

                        if (!failedFolder)
                        {
                            WriteResultFile(fullTargetPath, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered, newFileContents);
                        }
                    }
                }
            }
        }
 private string FormatTSqlWithFormatter(string inputString, PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter formatter)
 {
     //free use is all very nice, but I REALLY don't want anyone linking to this web service from some
     // other site or app: they should just download the library and incorporate or host it directly.
     // (assuming the project is GPL-compatible)
     //
     string allowedHost = System.Configuration.ConfigurationSettings.AppSettings["ReferrerHostValidation"];
     //no error handling, just do the bare (safe) minimum.
     if (string.IsNullOrEmpty(allowedHost)
         || (Context.Request.UrlReferrer != null
             && Context.Request.UrlReferrer.Host != null
             && Context.Request.UrlReferrer.Host.Equals(allowedHost)
             )
         )
     {
         PoorMansTSqlFormatterLib.SqlFormattingManager fullFormatter = new PoorMansTSqlFormatterLib.SqlFormattingManager(new PoorMansTSqlFormatterLib.Formatters.HtmlPageWrapper(formatter));
         return fullFormatter.Format(inputString);
     }
     else
     {
         return string.Format("Sorry, this web service can only be called from code hosted at {0}.", allowedHost);
     }
 }
 private void MenuOptionsCallback(object sender, EventArgs e)
 {
     GetFormatHotkey();
     SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));
     if (settings.ShowDialog() == DialogResult.OK)
     {
         SetFormatHotkey();
         _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
     }
 }
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool   isSqlFile     = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string        fullText  = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                        {
                            selection.SwapAnchor();
                        }
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                        {
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        }
                        string selectionText       = selection.Text;
                        bool   formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;
                        int    cursorPoint         = selection.ActivePoint.AbsoluteCharOffset;

                        string textToFormat  = formatSelectionOnly ? selectionText : fullText;
                        bool   errorsFound   = false;
                        string formattedText = _formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                        {
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;
                        }

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                //if selection just delete/insert, so the active point is at the end of the selection
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                            {
                                //if whole doc then replace all text, and put the cursor approximately where it was (using proportion of text total length before and after)
                                int newPosition = (int)Math.Round(1.0 * cursorPoint * formattedText.Length / textToFormat.Length, 0, MidpointRounding.AwayFromZero);
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                                ((TextSelection)(_applicationObject.ActiveDocument.Selection)).MoveToAbsoluteOffset(newPosition, false);
                            }
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    GetFormatHotkey();
                    SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                        _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
                    }
                    settings.Dispose();
                }
            }
        }
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool isSqlFile = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string fullText = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                            selection.SwapAnchor();
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        string selectionText = selection.Text;
                        bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;

                        string textToFormat = formatSelectionOnly ? selectionText : fullText;
                        bool errorsFound = false;
                        string formattedText = _formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    GetFormatHotkey();
                    SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                        _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
                    }
                    settings.Dispose();
                }
            }
        }
		/// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
		/// <param term='commandName'>The name of the command to execute.</param>
		/// <param term='executeOption'>Describes how the command should be run.</param>
		/// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
		/// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
		/// <param term='handled'>Informs the caller if the command was handled or not.</param>
		/// <seealso class='Exec' />
		public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
		{
			handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool isSqlFile = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string fullText = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater) 
                            selection.SwapAnchor();
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" ")) 
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        string selectionText = selection.Text;
                        bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;
						int cursorPoint = selection.ActivePoint.AbsoluteCharOffset;

                        string textToFormat = formatSelectionOnly ? selectionText : fullText;
                        bool errorsFound = false;
                        string formattedText = _formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;

                        if (!abortFormatting)
                        {
							if (formatSelectionOnly)
							{
								//if selection just delete/insert, so the active point is at the end of the selection
								selection.Delete(1);
								selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
							}
							else
							{
								//if whole doc then replace all text, and put the cursor approximately where it was (using proportion of text total length before and after)
								int newPosition = (int)Math.Round(1.0 * cursorPoint * formattedText.Length / textToFormat.Length, 0, MidpointRounding.AwayFromZero);
								ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
								((TextSelection)(_applicationObject.ActiveDocument.Selection)).MoveToAbsoluteOffset(newPosition, false);
							}
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    GetFormatHotkey();
                    SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                        _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
                    }
                    settings.Dispose();
                }
            }
		}
示例#24
0
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool   isSqlFile     = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string        fullText  = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                        {
                            selection.SwapAnchor();
                        }
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                        {
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        }
                        string selectionText       = selection.Text;
                        bool   formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;


                        string textToFormat = formatSelectionOnly ? selectionText : fullText;
                        var    formatter    = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                            Properties.Settings.Default.IndentString.Replace("\\t", "\t"),
                            Properties.Settings.Default.SpacesPerTab,
                            Properties.Settings.Default.MaxLineWidth,
                            Properties.Settings.Default.ExpandCommaLists,
                            Properties.Settings.Default.TrailingCommas,
                            Properties.Settings.Default.SpaceAfterExpandedComma,
                            Properties.Settings.Default.ExpandBooleanExpressions,
                            Properties.Settings.Default.ExpandCaseStatements,
                            Properties.Settings.Default.ExpandBetweenConditions,
                            Properties.Settings.Default.BreakJoinOnSections,
                            Properties.Settings.Default.UppercaseKeywords,
                            false,
                            Properties.Settings.Default.KeywordStandardization
                            );
                        formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix");
                        var    formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);
                        bool   errorsFound       = false;
                        string formattedText     = formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                        {
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;
                        }

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                            {
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                            }
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    SettingsForm settings = new SettingsForm();
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                    }
                    settings.Dispose();
                }
            }
        }
示例#25
0
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool   isSqlFile     = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string        fullText  = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                        {
                            selection.SwapAnchor();
                        }
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                        {
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        }
                        string selectionText       = selection.Text;
                        bool   formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;


                        string textToFormat  = formatSelectionOnly ? selectionText : fullText;
                        bool   errorsFound   = false;
                        string formattedText = _formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                        {
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;
                        }

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                            {
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                            }
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName));
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                        _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default);
                    }
                    settings.Dispose();
                }
            }
        }
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param term='commandName'>The name of the command to execute.</param>
        /// <param term='executeOption'>Describes how the command should be run.</param>
        /// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param term='handled'>Informs the caller if the command was handled or not.</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow"))
                {
                    string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName);
                    bool isSqlFile = fileExtension.ToUpper().Equals(".SQL");

                    if (isSqlFile ||
                        MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string fullText = SelectAllCodeFromDocument(_applicationObject.ActiveDocument);
                        TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
                        if (!selection.IsActiveEndGreater)
                            selection.SwapAnchor();
                        if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" "))
                            selection.CharLeft(true, 1); //newline counts as a distance of one.
                        string selectionText = selection.Text;
                        bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length;

                        string textToFormat = formatSelectionOnly ? selectionText : fullText;
                        var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                            Properties.Settings.Default.IndentString.Replace("\\t", "\t"),
                            Properties.Settings.Default.SpacesPerTab,
                            Properties.Settings.Default.MaxLineWidth,
                            Properties.Settings.Default.ExpandCommaLists,
                            Properties.Settings.Default.TrailingCommas,
                            Properties.Settings.Default.SpaceAfterExpandedComma,
                            Properties.Settings.Default.ExpandBooleanExpressions,
                            Properties.Settings.Default.ExpandCaseStatements,
                            Properties.Settings.Default.ExpandBetweenConditions,
                            Properties.Settings.Default.BreakJoinOnSections,
                            Properties.Settings.Default.UppercaseKeywords,
                            false,
                            Properties.Settings.Default.KeywordStandardization
                            );
                        formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix");
                        var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);
                        bool errorsFound = false;
                        string formattedText = formattingManager.Format(textToFormat, ref errorsFound);

                        bool abortFormatting = false;
                        if (errorsFound)
                            abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes;

                        if (!abortFormatting)
                        {
                            if (formatSelectionOnly)
                            {
                                selection.Delete(1);
                                selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText);
                            }
                            else
                                ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText);
                        }
                    }

                    handled = true;
                    return;
                }
                if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions"))
                {
                    SettingsForm settings = new SettingsForm();
                    if (settings.ShowDialog() == DialogResult.OK)
                    {
                        SetFormatHotkey();
                    }
                    settings.Dispose();
                }
            }
        }
示例#27
0
        static int Main(string[] args)
        {
            bool verbose            = false;
            bool allowParsingErrors = true;

            if (verbose)
            {
                Console.WriteLine("sqlipf");
            }

            string inputSQL = "select foo from bar where car";
            //inputSQL = Clipboard.GetText();
            //Console.WriteLine("GetText:" + inputSQL);
            string afs = PoorMansTSqlFormatterLib.SqlFormattingManager.AutoFormat();

            if (verbose)
            {
                Console.WriteLine(afs);
            }
            Clipboard.SetText(afs);
            Console.WriteLine("done!");
            //Console.ReadLine();

            return(0);

            //string formattedSQL = ((new PoorMansTSqlFormatterLib.SqlFormattingManager())).Format(inputSQL);
            //Console.WriteLine(formattedSQL);
            return(0);

            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
            {
                KeywordStandardization   = true,
                IndentString             = "\t",
                SpacesPerTab             = 4,
                MaxLineWidth             = 999,
                NewStatementLineBreaks   = 2,
                NewClauseLineBreaks      = 1,
                TrailingCommas           = false,
                SpaceAfterExpandedComma  = false,
                ExpandBetweenConditions  = true,
                ExpandBooleanExpressions = true,
                ExpandCaseStatements     = true,
                ExpandCommaLists         = true,
                BreakJoinOnSections      = false,
                UppercaseKeywords        = true,
                ExpandInLists            = true
            };

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(options);
            //formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            if (!string.IsNullOrEmpty(inputSQL))
            {
                string    formattedOutput = null;
                bool      parsingError    = false;
                Exception parseException  = null;
                try
                {
                    formattedOutput = formattingManager.Format(inputSQL, ref parsingError);
                    Console.WriteLine(formattedOutput);
                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors)
                    {
                        parsingError = false;
                    }
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError   = true;
                }
            }

            return(0);
        }
示例#28
0
        static int Main(string[] args)
        {
            //formatter engine option defaults
            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
                {
                    KeywordStandardization = true,
                    IndentString = "\t",
                    SpacesPerTab = 4,
                    MaxLineWidth = 999,
                    TrailingCommas = false,
                    SpaceAfterExpandedComma = false,
                    ExpandBetweenConditions = true,
                    ExpandBooleanExpressions = true,
                    ExpandCaseStatements = true,
                    ExpandCommaLists = true,
                    BreakJoinOnSections = false,
                    UppercaseKeywords = true
                };

            //bulk formatter options
            bool allowParsingErrors = false;
            List<string> extensions = new List<string>();
            bool backups = true;
            bool recursiveSearch = false;
            string outputFileOrFolder = null;
            string uiLangCode = null;

            //flow/tracking switches
            bool showUsageFriendly = false;
            bool showUsageError = false;

            OptionSet p = new OptionSet()
              .Add("is|indentString=", delegate(string v) { options.IndentString = v; })
              .Add("st|spacesPerTab=", delegate(string v) { options.SpacesPerTab = int.Parse(v); })
              .Add("mw|maxLineWidth=", delegate(string v) { options.MaxLineWidth = int.Parse(v); })
              .Add("tc|trailingCommas", delegate(string v) { options.TrailingCommas = v != null; })
              .Add("sac|spaceAfterExpandedComma", delegate(string v) { options.SpaceAfterExpandedComma = v != null; })
              .Add("ebc|expandBetweenConditions", delegate(string v) { options.ExpandBetweenConditions = v != null; })
              .Add("ebe|expandBooleanExpressions", delegate(string v) { options.ExpandBooleanExpressions = v != null; })
              .Add("ecs|expandCaseStatements", delegate(string v) { options.ExpandCaseStatements = v != null; })
              .Add("ecl|expandCommaLists", delegate(string v) { options.ExpandCommaLists = v != null; })
              .Add("bjo|breakJoinOnSections", delegate(string v) { options.BreakJoinOnSections = v != null; })
              .Add("uk|uppercaseKeywords", delegate(string v) { options.UppercaseKeywords = v != null; })
              .Add("sk|standardizeKeywords", delegate(string v) { options.KeywordStandardization = v != null; })

              .Add("ae|allowParsingErrors", delegate(string v) { allowParsingErrors = v != null; })
              .Add("e|extensions=", delegate(string v) { extensions.Add((v.StartsWith(".") ? "" : ".") + v); })
              .Add("r|recursive", delegate(string v) { recursiveSearch = v != null; })
              .Add("b|backups", delegate(string v) { backups = v != null; })
              .Add("o|outputFileOrFolder=", delegate(string v) { outputFileOrFolder = v; })
              .Add("l|languageCode=", delegate(string v) { uiLangCode = v; })
              .Add("h|?|help", delegate(string v) { showUsageFriendly = v != null; })
                  ;

            //first parse the args
            List<string> remainingArgs = p.Parse(args);

            //then switch language if necessary
            if (uiLangCode != null)
            {
                uiLangCode = uiLangCode.ToUpperInvariant();
                if (!uiLangCode.Equals(UILANGUAGE_EN)
                    && !uiLangCode.Equals(UILANGUAGE_FR)
                    && !uiLangCode.Equals(UILANGUAGE_ES)
                    )
                {
                    showUsageError = true;
                    //get the resource manager with default language, before displaying error.
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedLanguageErrorMessage"));
                }
                else
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(uiLangCode);
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    //get the resource manager AFTER setting language as requested.
                }
            }
            else
            {
                _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
            }

            //nasty trick to figure out whether we're in a pipeline or not
            bool throwAwayValue;
            string stdInput = null;
            try
            {
                throwAwayValue = System.Console.KeyAvailable;
            }
            catch (InvalidOperationException)
            {
                Console.InputEncoding = Encoding.UTF8;
                stdInput = System.Console.In.ReadToEnd();
            }

            //then complain about missing input or unrecognized args
            if (string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 0)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("NoInputErrorMessage"));
            }
            else if ((!string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 1) || remainingArgs.Count > 1)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedArgumentsErrorMessage"));
            }

            if (extensions.Count == 0)
                extensions.Add(".sql");

            if (showUsageFriendly || showUsageError)
            {
                TextWriter outStream = showUsageFriendly ? Console.Out : Console.Error;
                outStream.WriteLine(_generalResourceManager.GetString("ProgramSummary"));
                outStream.WriteLine("v" + Assembly.GetExecutingAssembly().GetName().Version.ToString());
                outStream.WriteLine(_generalResourceManager.GetString("ProgramUsageNotes"));
                return 1;
            }

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(options);
            formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            bool warningEncountered = false;
            if (!string.IsNullOrEmpty(stdInput))
            {
                string formattedOutput = null;
                bool parsingError = false;
                Exception parseException = null;
                try
                {
                    formattedOutput = formattingManager.Format(stdInput, ref parsingError);

                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors) parsingError = false;
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError = true;
                }

                if (parsingError)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ParsingErrorWarningMessage"), "STDIN"));
                    if (parseException != null)
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), parseException.Message));
                    warningEncountered = true;
                }
                else
                {
                    if (!string.IsNullOrEmpty(outputFileOrFolder))
                    {
                        WriteResultFile(outputFileOrFolder, null, null, ref warningEncountered, formattedOutput);
                    }
                    else
                    {
                        Console.OutputEncoding = Encoding.UTF8;
                        Console.Out.WriteLine(formattedOutput);
                    }
                }

            }
            else
            {
                System.IO.DirectoryInfo baseDirectory = null;
                string searchPattern = Path.GetFileName(remainingArgs[0]);
                string baseDirectoryName = Path.GetDirectoryName(remainingArgs[0]);
                if (baseDirectoryName.Length == 0)
                {
                    baseDirectoryName = ".";
                    if (searchPattern.Equals("."))
                        searchPattern = "";
                }
                System.IO.FileSystemInfo[] matchingObjects = null;
                try
                {
                    baseDirectory = new System.IO.DirectoryInfo(baseDirectoryName);
                    if (searchPattern.Length > 0)
                    {
                        if (recursiveSearch)
                            matchingObjects = baseDirectory.GetFileSystemInfos(searchPattern);
                        else
                            matchingObjects = baseDirectory.GetFiles(searchPattern);
                    }
                    else
                    {
                        if (recursiveSearch)
                            matchingObjects = baseDirectory.GetFileSystemInfos();
                        else
                            matchingObjects = new FileSystemInfo[0];
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("PathPatternErrorMessage"), e.Message));
                    return 2;
                }

                System.IO.StreamWriter singleFileWriter = null;
                string replaceFromFolderPath = null;
                string replaceToFolderPath = null;
                if (!string.IsNullOrEmpty(outputFileOrFolder))
                {
                    //ignore the backups setting - wouldn't make sense to back up the source files if we're
                    // writing to another file anyway...
                    backups = false;

                    if (Directory.Exists(outputFileOrFolder)
                        && (File.GetAttributes(outputFileOrFolder) & FileAttributes.Directory) == FileAttributes.Directory
                        )
                    {
                        replaceFromFolderPath = baseDirectory.FullName;
                        replaceToFolderPath = new DirectoryInfo(outputFileOrFolder).FullName;
                    }
                    else
                    {
                        try
                        {
                            //let's not worry too hard about releasing this resource - this is a command-line program,
                            // when it ends or dies all will be released anyway.
                            singleFileWriter = new StreamWriter(outputFileOrFolder);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("OutputFileCreationErrorMessage"), e.Message));
                            return 3;
                        }
                    }
                }

                if (!ProcessSearchResults(extensions, backups, allowParsingErrors, formattingManager, matchingObjects, singleFileWriter, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered))
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("NoFilesFoundWarningMessage"), remainingArgs[0], string.Join(",", extensions.ToArray())));
                    return 4;
                }

                if (singleFileWriter != null)
                {
                    singleFileWriter.Flush();
                    singleFileWriter.Close();
                    singleFileWriter.Dispose();
                }
            }

            if (warningEncountered)
                return 5; //general "there were warnings" return code
            else
                return 0; //we got there, did something, and received no (handled) errors!
        }
示例#29
0
 private string FormatTSqlWithFormatter(string inputString, PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter formatter)
 {
     PoorMansTSqlFormatterLib.SqlFormattingManager fullFormatter = new PoorMansTSqlFormatterLib.SqlFormattingManager(new PoorMansTSqlFormatterLib.Formatters.HtmlPageWrapper(formatter));
     return(fullFormatter.Format(inputString));
 }