示例#1
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));
        }
        private void SetFormatter()
        {
            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter innerFormatter;
            if (radio_Formatting_Standard.Checked)
            {
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                    txt_Indent.Text,
                    int.Parse(txt_IndentWidth.Text),
                    int.Parse(txt_MaxWidth.Text),
                    chk_ExpandCommaLists.Checked,
                    chk_TrailingCommas.Checked,
                    chk_SpaceAfterComma.Checked,
                    chk_ExpandBooleanExpressions.Checked,
                    chk_ExpandCaseStatements.Checked,
                    chk_ExpandBetweenConditions.Checked,
                    chk_BreakJoinOnSections.Checked,
                    chk_UppercaseKeywords.Checked,
                    chk_Coloring.Checked,
                    chk_EnableKeywordStandardization.Checked
                    );
            }
            else
            {
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(chk_IdentityColoring.Checked);
            }

            innerFormatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix");
            _formatter = new PoorMansTSqlFormatterLib.Formatters.HtmlPageWrapper(innerFormatter);
        }
示例#3
0
        public static PoorMansTSqlFormatterLib.SqlFormattingManager GetFormattingManager(ISqlSettings settings)
        {
            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                settings.IndentString.Replace("\\t", "\t").Replace("\\s", " "),
                settings.SpacesPerTab,
                settings.MaxLineWidth,
                settings.ExpandCommaLists,
                settings.TrailingCommas,
                settings.SpaceAfterExpandedComma,
                settings.ExpandBooleanExpressions,
                settings.ExpandCaseStatements,
                settings.ExpandBetweenConditions,
                settings.BreakJoinOnSections,
                settings.UppercaseKeywords,
                false,
                settings.KeywordStandardization
                );

            ResourceManager _generalResourceManager = new ResourceManager("PoorMansTSqlFormatterPluginShared.GeneralLanguageContent", Assembly.GetExecutingAssembly());

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

            return(formattingManager);
        }
 public static PoorMansTSqlFormatterLib.SqlFormattingManager GetFormattingManager(ISqlSettings settings)
 {
     var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(settings.Options);
     
     ResourceManager _generalResourceManager = new ResourceManager("PoorMansTSqlFormatterPluginShared.GeneralLanguageContent", Assembly.GetExecutingAssembly());
     formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + System.Environment.NewLine;
     var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);
     return formattingManager;
 }
示例#5
0
        public static PoorMansTSqlFormatterLib.SqlFormattingManager GetFormattingManager(ISqlSettings settings)
        {
            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(settings.Options);

            ResourceManager _generalResourceManager = new ResourceManager("PoorMansTSqlFormatterPluginShared.GeneralLanguageContent", Assembly.GetExecutingAssembly());

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

            return(formattingManager);
        }
        public string FormatTSqlWithOptions(
            string inputString,
            bool reFormat,
            string indent,
            int spacesPerTab,
            int maxLineWidth,
            bool expandCommaLists,
            bool trailingCommas,
            bool spaceAfterExpandedComma,
            bool expandBooleanExpressions,
            bool expandCaseStatements,
            bool expandBetweenConditions,
            bool breakJoinOnSections,
            bool uppercaseKeywords,
            bool coloring,
            bool keywordStandardization,
            bool useParseErrorPlaceholder
            )
        {
            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter formatter = null;
            if (reFormat)
            {
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                    indent,
                    spacesPerTab,
                    maxLineWidth,
                    expandCommaLists,
                    trailingCommas,
                    spaceAfterExpandedComma,
                    expandBooleanExpressions,
                    expandCaseStatements,
                    expandBetweenConditions,
                    breakJoinOnSections,
                    uppercaseKeywords,
                    coloring,
                    keywordStandardization
                    );
            }
            else
            {
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(coloring);
            }

            if (useParseErrorPlaceholder)
            {
                formatter.ErrorOutputPrefix = "{PARSEERRORPLACEHOLDER}";
            }

            return(FormatTSqlWithFormatter(inputString, formatter));
        }
示例#7
0
        public static string Format(string sql)
        {
            var tokenizer = new PoorMansTSqlFormatterLib.Tokenizers.TSqlStandardTokenizer();
            var parser = new PoorMansTSqlFormatterLib.Parsers.TSqlStandardParser();

            var tokenizedSql = tokenizer.TokenizeSQL(sql);

            var parsedSql = parser.ParseSQL(tokenizedSql);

            var innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter();

            //webBrowser_OutputSql.SetHTML(_formatter.FormatSQLTree(parsedSql));
            return innerFormatter.FormatSQLTree(parsedSql);
        }
示例#8
0
        public static string Format(string sql)
        {
            var tokenizer = new PoorMansTSqlFormatterLib.Tokenizers.TSqlStandardTokenizer();
            var parser    = new PoorMansTSqlFormatterLib.Parsers.TSqlStandardParser();

            var tokenizedSql = tokenizer.TokenizeSQL(sql);

            var parsedSql = parser.ParseSQL(tokenizedSql);

            var innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter();

            //webBrowser_OutputSql.SetHTML(_formatter.FormatSQLTree(parsedSql));
            return(innerFormatter.FormatSQLTree(parsedSql));
        }
        /// <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));
        }
示例#10
0
        private void SetFormatter()
        {
            ISqlTreeFormatter innerFormatter;

            if (radio_Formatting_Standard.Checked)
            {
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
                {
                    IndentString             = txt_Indent.Text,
                    SpacesPerTab             = int.Parse(txt_IndentWidth.Text),
                    MaxLineWidth             = int.Parse(txt_MaxWidth.Text),
                    ExpandCommaLists         = chk_ExpandCommaLists.Checked,
                    TrailingCommas           = chk_TrailingCommas.Checked,
                    SpaceAfterExpandedComma  = chk_SpaceAfterComma.Checked,
                    ExpandBooleanExpressions = chk_ExpandBooleanExpressions.Checked,
                    ExpandCaseStatements     = chk_ExpandCaseStatements.Checked,
                    ExpandBetweenConditions  = chk_ExpandBetweenConditions.Checked,
                    ExpandInLists            = chk_ExpandInLists.Checked,
                    BreakJoinOnSections      = chk_BreakJoinOnSections.Checked,
                    UppercaseKeywords        = chk_UppercaseKeywords.Checked,
                    HTMLColoring             = chk_Coloring.Checked,
                    KeywordStandardization   = chk_EnableKeywordStandardization.Checked,
                    NewStatementLineBreaks   = int.Parse(txt_StatementBreaks.Text),
                    NewClauseLineBreaks      = int.Parse(txt_ClauseBreaks.Text)
                });
            }
            else if (radio_Formatting_Identity.Checked)
            {
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(chk_IdentityColoring.Checked);
            }
            else
            {
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlObfuscatingFormatter(
                    chk_RandomizeKeywordCase.Checked,
                    chk_RandomizeColor.Checked,
                    chk_RandomizeLineLength.Checked,
                    chk_PreserveComments.Checked,
                    chk_KeywordSubstitution.Checked
                    );
            }

            innerFormatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            _formatter = new PoorMansTSqlFormatterLib.Formatters.HtmlPageWrapper(innerFormatter);
        }
示例#11
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));
        }
示例#12
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);
        }
示例#13
0
        public static PoorMansTSqlFormatterLib.SqlFormattingManager GetFormattingManager(ISqlSettings settings)
        {
            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                settings.IndentString.Replace("\\t", "\t").Replace("\\s", " "),
                settings.SpacesPerTab,
                settings.MaxLineWidth,
                settings.ExpandCommaLists,
                settings.TrailingCommas,
                settings.SpaceAfterExpandedComma,
                settings.ExpandBooleanExpressions,
                settings.ExpandCaseStatements,
                settings.ExpandBetweenConditions,
                settings.BreakJoinOnSections,
                settings.UppercaseKeywords,
                false,
                settings.KeywordStandardization
                );

            ResourceManager _generalResourceManager = new ResourceManager("PoorMansTSqlFormatterPluginShared.GeneralLanguageContent", Assembly.GetExecutingAssembly());
            formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + System.Environment.NewLine;
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);
            return formattingManager;
        }
        public string FormatTSqlWithOptions(
            string inputString,
            bool reFormat,
            string indent,
            int spacesPerTab,
            int maxLineWidth,
            bool expandCommaLists,
            bool trailingCommas,
            bool spaceAfterExpandedComma,
            bool expandBooleanExpressions,
            bool expandCaseStatements,
            bool expandBetweenConditions,
            bool breakJoinOnSections,
            bool uppercaseKeywords,
            bool coloring,
            bool keywordStandardization,
            bool useParseErrorPlaceholder,
            bool obfuscate,
            bool randomizeColor,
            bool randomizeLineLengths,
            bool randomizeKeywordCase,
            bool preserveComments,
            bool enableKeywordSubstitution
            )
        {
            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter formatter = null;
            if (reFormat)
            {
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
                    {
                        IndentString = indent,
                        SpacesPerTab = spacesPerTab,
                        MaxLineWidth = maxLineWidth,
                        ExpandCommaLists = expandCommaLists,
                        TrailingCommas = trailingCommas,
                        SpaceAfterExpandedComma = spaceAfterExpandedComma,
                        ExpandBooleanExpressions = expandBooleanExpressions,
                        ExpandCaseStatements = expandCaseStatements,
                        ExpandBetweenConditions = expandBetweenConditions,
                        BreakJoinOnSections = breakJoinOnSections,
                        UppercaseKeywords = uppercaseKeywords,
                        HTMLColoring = coloring,
                        KeywordStandardization = keywordStandardization
                    });

            }
            else if (obfuscate)
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlObfuscatingFormatter(
                    randomizeKeywordCase,
                    randomizeColor,
                    randomizeLineLengths,
                    preserveComments,
                    enableKeywordSubstitution
                    );
            else
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(coloring);

            if (useParseErrorPlaceholder)
                formatter.ErrorOutputPrefix = "{PARSEERRORPLACEHOLDER}";

            return FormatTSqlWithFormatter(inputString, formatter);
        }
        private void SetFormatter()
        {
            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter innerFormatter;
            if (radio_Formatting_Standard.Checked)
            {
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
                    {
                        IndentString = txt_Indent.Text,
                        SpacesPerTab = int.Parse(txt_IndentWidth.Text),
                        MaxLineWidth = int.Parse(txt_MaxWidth.Text),
                        ExpandCommaLists = chk_ExpandCommaLists.Checked,
                        TrailingCommas = chk_TrailingCommas.Checked,
                        SpaceAfterExpandedComma = chk_SpaceAfterComma.Checked,
                        ExpandBooleanExpressions = chk_ExpandBooleanExpressions.Checked,
                        ExpandCaseStatements = chk_ExpandCaseStatements.Checked,
						ExpandBetweenConditions = chk_ExpandBetweenConditions.Checked,
						ExpandInLists = chk_ExpandInLists.Checked,
						BreakJoinOnSections = chk_BreakJoinOnSections.Checked,
                        UppercaseKeywords = chk_UppercaseKeywords.Checked,
                        HTMLColoring = chk_Coloring.Checked,
						KeywordStandardization = chk_EnableKeywordStandardization.Checked,
						NewStatementLineBreaks = int.Parse(txt_StatementBreaks.Text),
						NewClauseLineBreaks = int.Parse(txt_ClauseBreaks.Text)
					});
            }
            else if (radio_Formatting_Identity.Checked)
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(chk_IdentityColoring.Checked);
            else
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlObfuscatingFormatter(
                    chk_RandomizeKeywordCase.Checked,
                    chk_RandomizeColor.Checked,
                    chk_RandomizeLineLength.Checked,
                    chk_PreserveComments.Checked,
                    chk_KeywordSubstitution.Checked
                    );

            innerFormatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            _formatter = new PoorMansTSqlFormatterLib.Formatters.HtmlPageWrapper(innerFormatter);
        }
        public string FormatTSqlWithOptions(
            string inputString,
            bool reFormat,
            string indent,
            int spacesPerTab,
            int maxLineWidth,
            bool expandCommaLists,
            bool trailingCommas,
            bool spaceAfterExpandedComma,
            bool expandBooleanExpressions,
            bool expandCaseStatements,
            bool expandBetweenConditions,
            bool breakJoinOnSections,
            bool uppercaseKeywords,
            bool coloring,
            bool keywordStandardization,
            bool useParseErrorPlaceholder
            )
        {
            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter formatter = null;
            if (reFormat)
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                    indent,
                    spacesPerTab,
                    maxLineWidth,
                    expandCommaLists,
                    trailingCommas,
                    spaceAfterExpandedComma,
                    expandBooleanExpressions,
                    expandCaseStatements,
                    expandBetweenConditions,
                    breakJoinOnSections,
                    uppercaseKeywords,
                    coloring,
                    keywordStandardization
                    );
            else
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(coloring);

            if (useParseErrorPlaceholder)
                formatter.ErrorOutputPrefix = "{PARSEERRORPLACEHOLDER}";

            return FormatTSqlWithFormatter(inputString, formatter);
        }
示例#17
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();
                }
            }
        }
示例#18
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!
        }
示例#19
0
        public string FormatTSqlWithOptions(
            string inputString,
            bool reFormat,
            string indent,
            int spacesPerTab,
            int maxLineWidth,
            int statementBreaks,
            int clauseBreaks,
            bool expandCommaLists,
            bool trailingCommas,
            bool spaceAfterExpandedComma,
            bool expandBooleanExpressions,
            bool expandCaseStatements,
            bool expandBetweenConditions,
            bool breakJoinOnSections,
            bool uppercaseKeywords,
            bool coloring,
            bool keywordStandardization,
            bool useParseErrorPlaceholder,
            bool obfuscate,
            bool randomizeColor,
            bool randomizeLineLengths,
            bool randomizeKeywordCase,
            bool preserveComments,
            bool enableKeywordSubstitution,
            bool expandInLists
            )
        {
            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter formatter = null;
            if (reFormat)
            {
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
                {
                    IndentString             = indent,
                    SpacesPerTab             = spacesPerTab,
                    MaxLineWidth             = maxLineWidth,
                    NewStatementLineBreaks   = statementBreaks,
                    NewClauseLineBreaks      = clauseBreaks,
                    ExpandCommaLists         = expandCommaLists,
                    TrailingCommas           = trailingCommas,
                    SpaceAfterExpandedComma  = spaceAfterExpandedComma,
                    ExpandBooleanExpressions = expandBooleanExpressions,
                    ExpandCaseStatements     = expandCaseStatements,
                    ExpandBetweenConditions  = expandBetweenConditions,
                    BreakJoinOnSections      = breakJoinOnSections,
                    UppercaseKeywords        = uppercaseKeywords,
                    HTMLColoring             = coloring,
                    KeywordStandardization   = keywordStandardization,
                    ExpandInLists            = expandInLists
                });
            }
            else if (obfuscate)
            {
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlObfuscatingFormatter(
                    randomizeKeywordCase,
                    randomizeColor,
                    randomizeLineLengths,
                    preserveComments,
                    enableKeywordSubstitution
                    );
            }
            else
            {
                formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(coloring);
            }

            if (useParseErrorPlaceholder)
            {
                formatter.ErrorOutputPrefix = "{PARSEERRORPLACEHOLDER}";
            }

            return(FormatTSqlWithFormatter(inputString, formatter));
        }
示例#20
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!
            }
        }
        /// <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();
                }
            }
        }
        private void SetFormatter()
        {
            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter innerFormatter;
            if (radio_Formatting_Standard.Checked)
            {
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                    txt_Indent.Text,
                    int.Parse(txt_IndentWidth.Text),
                    int.Parse(txt_MaxWidth.Text),
                    chk_ExpandCommaLists.Checked,
                    chk_TrailingCommas.Checked,
                    chk_SpaceAfterComma.Checked,
                    chk_ExpandBooleanExpressions.Checked,
                    chk_ExpandCaseStatements.Checked,
                    chk_ExpandBetweenConditions.Checked,
                    chk_BreakJoinOnSections.Checked,
                    chk_UppercaseKeywords.Checked,
                    chk_Coloring.Checked,
                    chk_EnableKeywordStandardization.Checked
                    );
            }
            else
                innerFormatter = new PoorMansTSqlFormatterLib.Formatters.TSqlIdentityFormatter(chk_IdentityColoring.Checked);

            innerFormatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix");
            _formatter = new PoorMansTSqlFormatterLib.Formatters.HtmlPageWrapper(innerFormatter);
        }
示例#23
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);
        }