Ejemplo n.º 1
0
        private async Task<Document> MakeUppercaseAsync(Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken)
        {
            var argumentExpression = invocation.ArgumentList.Arguments.FirstOrDefault()?.Expression;
            var argumentContents = argumentExpression.ToString().Replace("\"", string.Empty);

            var quoter = new Quoter();
            var roslynCalls = SyntaxFactory.ParseExpression(quoter.Quote(argumentContents));
            var newRoot = (await document.GetSyntaxRootAsync()).ReplaceNode(invocation, roslynCalls);
            var newDocument = document.WithSyntaxRoot(newRoot);
            
            return newDocument;
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var sourceText = "class C{}";
            var sourceNode = CSharpSyntaxTree.ParseText(sourceText).GetRoot() as CSharpSyntaxNode;
            var quoter = new Quoter
            {
                OpenParenthesisOnNewLine = false,
                ClosingParenthesisOnNewLine = false,
                UseDefaultFormatting = true
            };

            var generatedCode = quoter.Quote(sourceNode);

            Console.WriteLine(generatedCode);
        }
Ejemplo n.º 3
0
        public string Get(
            string sourceText,
            NodeKind nodeKind = NodeKind.CompilationUnit,
            bool openCurlyOnNewLine = false,
            bool closeCurlyOnNewLine = false,
            bool preserveOriginalWhitespace = false,
            bool keepRedundantApiCalls = false,
            bool avoidUsingStatic = false)
        {
            string responseText = "Quoter is currently down for maintenance. Please check back later.";
            if (string.IsNullOrEmpty(sourceText))
            {
                responseText = "Please specify the source text.";
            }
            else if (sourceText.Length > 2000)
            {
                responseText = "Only strings shorter than 2000 characters are supported; your input string is " + sourceText.Length + " characters long.";
            }
            else
            {
                try
                {
                    var quoter = new Quoter
                    {
                        OpenParenthesisOnNewLine = openCurlyOnNewLine,
                        ClosingParenthesisOnNewLine = closeCurlyOnNewLine,
                        UseDefaultFormatting = !preserveOriginalWhitespace,
                        RemoveRedundantModifyingCalls = !keepRedundantApiCalls,
                        ShortenCodeWithUsingStatic = !avoidUsingStatic
                    };

                    responseText = quoter.Quote(sourceText, nodeKind);
                }
                catch (Exception ex)
                {
                    responseText = ex.ToString();
                }
            }

            Response.Headers.Add("Cache-Control", new[] { "no-cache" });
            Response.Headers.Add("Pragma", new[] { "no-cache" });
            Response.Headers.Add("Expires", new[] { "-1" });
            Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type" });

            return responseText;
        }
Ejemplo n.º 4
0
        public HttpResponseMessage Get(
            string sourceText,
            NodeKind nodeKind = NodeKind.CompilationUnit,
            bool openCurlyOnNewLine = false,
            bool closeCurlyOnNewLine = false,
            bool preserveOriginalWhitespace = false,
            bool keepRedundantApiCalls = false,
            bool avoidUsingStatic = false)
        {
            string responseText = "Quoter is currently down for maintenance. Please check back later.";
            if (string.IsNullOrEmpty(sourceText))
            {
                responseText = "Please specify the source text.";
            }
            else if (sourceText.Length > 2000)
            {
                responseText = "Only strings shorter than 2000 characters are supported; your input string is " + sourceText.Length + " characters long.";
            }
            else
            {
                try
                {
                    var quoter = new Quoter
                    {
                        OpenParenthesisOnNewLine = openCurlyOnNewLine,
                        ClosingParenthesisOnNewLine = closeCurlyOnNewLine,
                        UseDefaultFormatting = !preserveOriginalWhitespace,
                        RemoveRedundantModifyingCalls = !keepRedundantApiCalls,
                        ShortenCodeWithUsingStatic = !avoidUsingStatic
                    };

                    responseText = quoter.Quote(sourceText, nodeKind);
                }
                catch (Exception ex)
                {
                    responseText = ex.ToString();
                }
            }

            responseText = HttpUtility.HtmlEncode(responseText);

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent(responseText, Encoding.UTF8, "text/html");
            return response;
        }
Ejemplo n.º 5
0
    private void Test(string sourceText, string expected, bool useDefaultFormatting = true)
    {
        var quoter = new Quoter
        {
            UseDefaultFormatting = useDefaultFormatting,
        };
        var actual = quoter.Quote(sourceText);
        Assert.AreEqual(expected, actual);

        Test(sourceText);
    }
Ejemplo n.º 6
0
 public override string Generate(RenameTableExpression expression)
 {
     return(string.Format("ALTER TABLE {0} RENAME TO {1};", Quoter.QuoteTableName(expression.OldName, expression.SchemaName), Quoter.Quote(expression.NewName)));
 }
Ejemplo n.º 7
0
 public override string Generate(RenameTableExpression expression)
 {
     return(String.Format(RenameTable, Quoter.QuoteTableName(expression.OldName), Quoter.QuoteTableName(expression.NewName)));
 }
Ejemplo n.º 8
0
 private bool ShouldInlineConstant <T>(Variable <T> constant)
 {
     return(Quoter.ShouldInlineType(typeof(T)) && !constant.IsDefined && !variablesToInfer.Contains(constant));
 }
Ejemplo n.º 9
0
 public override string Generate(DeleteForeignKeyExpression expression)
 {
     return(string.Format("ALTER TABLE {0} DROP CONSTRAINT {1};",
                          Quoter.QuoteTableName(expression.ForeignKey.ForeignTable, expression.ForeignKey.ForeignTableSchema),
                          Quoter.Quote(expression.ForeignKey.Name)));
 }
Ejemplo n.º 10
0
 public override string Generate(DeleteConstraintExpression expression)
 {
     return(string.Format("ALTER TABLE {0}.{1} DROP CONSTRAINT {2}", Quoter.QuoteSchemaName(expression.Constraint.SchemaName), Quoter.QuoteTableName(expression.Constraint.TableName), Quoter.Quote(expression.Constraint.ConstraintName)));
 }
Ejemplo n.º 11
0
 public override string Generate(AlterColumnExpression expression)
 {
     return(String.Format("ALTER TABLE {0}.{1} {2}", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), ((PostgresColumn)Column).GenerateAlterClauses(expression.Column)));
 }
Ejemplo n.º 12
0
        public IActionResult Get(
            string sourceText,
            NodeKind nodeKind               = NodeKind.CompilationUnit,
            bool openCurlyOnNewLine         = false,
            bool closeCurlyOnNewLine        = false,
            bool preserveOriginalWhitespace = false,
            bool keepRedundantApiCalls      = false,
            bool avoidUsingStatic           = false,
            bool generateLINQPad            = false)
        {
            string prefix = null;

            string responseText = "Quoter is currently down for maintenance. Please check back later.";

            if (string.IsNullOrEmpty(sourceText))
            {
                responseText = "Please specify the source text.";
            }
            else
            {
                try
                {
                    var quoter = new Quoter
                    {
                        OpenParenthesisOnNewLine      = openCurlyOnNewLine,
                        ClosingParenthesisOnNewLine   = closeCurlyOnNewLine,
                        UseDefaultFormatting          = !preserveOriginalWhitespace,
                        RemoveRedundantModifyingCalls = !keepRedundantApiCalls,
                        ShortenCodeWithUsingStatic    = !avoidUsingStatic
                    };

                    responseText = quoter.QuoteText(sourceText, nodeKind);

                    var          typedefTypeNames           = new[] { "BooleanTypedef", "GuidTypedef", "IntTypedef", "LongTypedef", "StringTypedef" };
                    const string structNameParameter        = "structName";
                    const string typeConverterNameParameter = "typeConverterName";
                    foreach (string typedefTypeName in typedefTypeNames)
                    {
                        responseText = responseText.Replace($"\"{typedefTypeName}\"", structNameParameter);
                        responseText = responseText.Replace($"\"{typedefTypeName}TypeConverter\"", typeConverterNameParameter);
                    }
                }
                catch (Exception ex)
                {
                    responseText = ex.ToString();

                    prefix = "Congratulations! You've found a bug in Quoter! Please open an issue at <a href=\"https://github.com/KirillOsenkov/RoslynQuoter/issues/new\" target=\"_blank\">https://github.com/KirillOsenkov/RoslynQuoter/issues/new</a> and paste the code you've typed above and this stack:";
                }
            }

            if (generateLINQPad)
            {
                var linqpadFile = $@"<Query Kind=""Expression"">
  <NuGetReference>Microsoft.CodeAnalysis.Compilers</NuGetReference>
  <NuGetReference>Microsoft.CodeAnalysis.CSharp</NuGetReference>
  <Namespace>static Microsoft.CodeAnalysis.CSharp.SyntaxFactory</Namespace>
  <Namespace>Microsoft.CodeAnalysis.CSharp.Syntax</Namespace>
  <Namespace>Microsoft.CodeAnalysis.CSharp</Namespace>
  <Namespace>Microsoft.CodeAnalysis</Namespace>
</Query>

{responseText}
";

                var responseBytes = Encoding.UTF8.GetBytes(linqpadFile);

                return(File(responseBytes, "application/octet-stream", "Quoter.linq"));
            }

            responseText = HttpUtility.HtmlEncode(responseText);

            if (prefix != null)
            {
                responseText = "<div class=\"error\"><p>" + prefix + "</p><p>" + responseText + "</p><p><br/>P.S. Sorry!</p></div>";
            }

            return(Ok(responseText));
        }
Ejemplo n.º 13
0
 public override string Generate(DeleteIndexExpression expression)
 {
     return(string.Format("DROP INDEX {0}.{1}", Quoter.QuoteSchemaName(expression.Index.SchemaName), Quoter.QuoteIndexName(expression.Index.Name)));
 }
Ejemplo n.º 14
0
        public override string Generate(DeleteDataExpression expression)
        {
            var deleteItems = new List <string>();


            if (expression.IsAllRows)
            {
                deleteItems.Add(string.Format(DeleteData, Quoter.QuoteTableName(expression.TableName), "1 = 1"));
            }
            else
            {
                foreach (var row in expression.Rows)
                {
                    var whereClauses = new List <string>();
                    foreach (KeyValuePair <string, object> item in row)
                    {
                        whereClauses.Add(string.Format("{0} {1} {2}", Quoter.QuoteColumnName(item.Key), item.Value == null ? "IS" : "=", Quoter.QuoteValue(item.Value)));
                    }

                    deleteItems.Add(string.Format(DeleteData, Quoter.QuoteTableName(expression.TableName), String.Join(" AND ", whereClauses.ToArray())));
                }
            }

            return(String.Join("; ", deleteItems.ToArray()));
        }
Ejemplo n.º 15
0
        public override string Generate(DeleteSequenceExpression expression)
        {
            var result = new StringBuilder(string.Format("DROP SEQUENCE "));

            result.AppendFormat("{0}.{1}", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteSequenceName(expression.SequenceName));

            return(result.ToString());
        }
Ejemplo n.º 16
0
        public override string Generate(UpdateDataExpression expression)
        {
            List <string> updateItems  = new List <string>();
            List <string> whereClauses = new List <string>();

            foreach (var item in expression.Set)
            {
                updateItems.Add(string.Format("{0} = {1}", Quoter.QuoteColumnName(item.Key), Quoter.QuoteValue(item.Value)));
            }

            foreach (var item in expression.Where)
            {
                whereClauses.Add(string.Format("{0} {1} {2}", Quoter.QuoteColumnName(item.Key), item.Value == null ? "IS" : "=", Quoter.QuoteValue(item.Value)));
            }

            return(String.Format(UpdateData, Quoter.QuoteTableName(expression.TableName), String.Join(", ", updateItems.ToArray()), String.Join(" AND ", whereClauses.ToArray())));
        }
Ejemplo n.º 17
0
 public override string Generate(DeleteForeignKeyExpression expression)
 {
     return(string.Format(DeleteConstraint, Quoter.QuoteTableName(expression.ForeignKey.ForeignTable), Quoter.QuoteColumnName(expression.ForeignKey.Name)));
 }
Ejemplo n.º 18
0
 public override string Generate(DeleteConstraintExpression expression)
 {
     return(string.Format(DeleteConstraint, Quoter.QuoteTableName(expression.Constraint.TableName), Quoter.Quote(expression.Constraint.ConstraintName)));
 }
Ejemplo n.º 19
0
 public override string Generate(DeleteIndexExpression expression)
 {
     return(String.Format(DropIndex, Quoter.QuoteIndexName(expression.Index.Name), Quoter.QuoteTableName(expression.Index.TableName)));
 }
Ejemplo n.º 20
0
 public override string Generate(RenameColumnExpression expression)
 {
     return(string.Format("ALTER TABLE {0}.{1} RENAME COLUMN {2} TO {3}", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), Quoter.QuoteColumnName(expression.OldName), Quoter.QuoteColumnName(expression.NewName)));
 }
Ejemplo n.º 21
0
 public override string Generate(DeleteDefaultConstraintExpression expression)
 {
     return(string.Format("ALTER TABLE {0}.{1} ALTER {2} DROP DEFAULT", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), Quoter.Quote(expression.ColumnName)));
 }
Ejemplo n.º 22
0
        public override string Generate(InsertDataExpression expression)
        {
            var result = new StringBuilder();

            foreach (var row in expression.Rows)
            {
                var columnNames = new List <string>();
                var columnData  = new List <object>();
                foreach (var item in row)
                {
                    columnNames.Add(item.Key);
                    columnData.Add(item.Value);
                }

                var columns = GetColumnList(columnNames);
                var data    = GetDataList(columnData);
                result.Append(String.Format("INSERT INTO {0}.{1} ({2}) VALUES ({3});", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), columns, data));
            }
            return(result.ToString());
        }
Ejemplo n.º 23
0
        public override string Generate(CreateTableExpression expression)
        {
            var tableName = Quoter.QuoteTableName(expression.TableName);

            return(string.Format("CREATE TABLE {0}.{1} ({2})", Quoter.QuoteSchemaName(expression.SchemaName), tableName, Column.Generate(expression.Columns, tableName)));
        }
Ejemplo n.º 24
0
 public override string Generate(CreateSchemaExpression expression)
 {
     return(string.Format("CREATE SCHEMA {0}", Quoter.QuoteSchemaName(expression.SchemaName)));
 }
Ejemplo n.º 25
0
 public override string Generate(CreateColumnExpression expression)
 {
     return(string.Format("ALTER TABLE {0}.{1} ADD {2}", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), Column.Generate(expression.Column)));
 }
Ejemplo n.º 26
0
 public override string Generate(AlterDefaultConstraintExpression expression)
 {
     return(String.Format("ALTER TABLE {0}.{1} ALTER {2} DROP DEFAULT, ALTER {2} {3}", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), Quoter.QuoteColumnName(expression.ColumnName), ((PostgresColumn)Column).FormatAlterDefaultValue(expression.ColumnName, expression.DefaultValue)));
 }
Ejemplo n.º 27
0
 public override string Generate(DeleteTableExpression expression)
 {
     return(string.Format("DROP TABLE {0};", Quoter.QuoteTableName(expression.TableName, expression.SchemaName)));
 }
Ejemplo n.º 28
0
        public override string Generate(DeleteDataExpression expression)
        {
            var result = new StringBuilder();

            if (expression.IsAllRows)
            {
                result.Append(String.Format("DELETE FROM {0}.{1};", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName)));
            }
            else
            {
                foreach (var row in expression.Rows)
                {
                    var where = String.Empty;
                    var i = 0;

                    foreach (var item in row)
                    {
                        if (i != 0)
                        {
                            where += " AND ";
                        }

                        where += String.Format("{0} {1} {2}", Quoter.QuoteColumnName(item.Key), item.Value == null ? "IS" : "=", Quoter.QuoteValue(item.Value));
                        i++;
                    }

                    result.Append(String.Format("DELETE FROM {0}.{1} WHERE {2};", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), where));
                }
            }

            return(result.ToString());
        }
Ejemplo n.º 29
0
        public override string Generate(CreateIndexExpression expression)
        {
            var result = new StringBuilder("CREATE");

            if (expression.Index.IsUnique)
            {
                result.Append(" UNIQUE");
            }

            result.Append(" INDEX {0} ON {1} (");

            var first = true;

            foreach (var column in expression.Index.Columns)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    result.Append(",");
                }

                result.Append(Quoter.QuoteColumnName(column.Name));
                result.Append(column.Direction == Direction.Ascending ? " ASC" : " DESC");
            }
            result.Append(");");

            return(string.Format(result.ToString(), Quoter.QuoteIndexName(expression.Index.Name), Quoter.QuoteTableName(expression.Index.TableName, expression.Index.SchemaName)));

            /*
             * var idx = String.Format(result.ToString(), expression.Index.Name, Quoter.QuoteSchemaName(expression.Index.SchemaName), expression.Index.TableName);
             * if (!expression.Index.IsClustered)
             *  return idx;
             *
             * // Clustered indexes in Postgres do not cluster updates/inserts to the table after the initial cluster operation is applied.
             * // To keep the clustered index up to date run CLUSTER TableName periodically
             *
             * return string.Format("{0}; CLUSTER {1}\"{2}\" ON \"{3}\"", idx, Quoter.QuoteSchemaName(expression.Index.SchemaName), expression.Index.TableName, expression.Index.Name);
             */
        }
Ejemplo n.º 30
0
    private static void Test(string sourceText, bool useDefaultFormatting, bool removeRedundantCalls, bool shortenCodeWithUsingStatic)
    {
        if (useDefaultFormatting)
        {
            sourceText = CSharpSyntaxTree
                .ParseText(sourceText)
                .GetRoot()
                .NormalizeWhitespace()
                .ToFullString();
        }

        var quoter = new Quoter
        {
            UseDefaultFormatting = useDefaultFormatting,
            RemoveRedundantModifyingCalls = removeRedundantCalls
        };
        var generatedCode = quoter.Quote(sourceText);

        var resultText = quoter.Evaluate(generatedCode);

        if (sourceText != resultText)
        {
            //File.WriteAllText(@"D:\1.txt", sourceText);
            //File.WriteAllText(@"D:\2.txt", resultText);
            //File.WriteAllText(@"D:\3.txt", generatedCode);
        }

        Assert.AreEqual(sourceText, resultText);
    }
Ejemplo n.º 31
0
 public override string Generate(AlterColumnExpression expression)
 {
     return(String.Format(AlterColumn, Quoter.QuoteTableName(expression.TableName), Column.Generate(expression.Column)));
 }
 public override string Generate(DeleteTableExpression expression)
 {
     return(string.Format(DropTable, ExpandTableName(Quoter.QuoteTableName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName))));
 }
Ejemplo n.º 33
0
    private static void Test(string sourceText, bool useDefaultFormatting, bool removeRedundantCalls)
    {
        if (useDefaultFormatting)
        {
            sourceText = CSharpSyntaxTree
                .ParseText(sourceText)
                .GetRoot()
                .NormalizeWhitespace()
                .ToFullString();
        }

        var quoter = new Quoter
        {
            UseDefaultFormatting = useDefaultFormatting,
            RemoveRedundantModifyingCalls = removeRedundantCalls
        };
        var generatedCode = quoter.Quote(sourceText);

        ////var evaluator = new Evaluator();
        ////var generatedNode = evaluator.Evaluate(generatedCode) as CompilationUnitSyntax;

        ////var resultText = generatedNode.ToFullString();

        ////if (sourceText != resultText)
        ////{
        ////    File.WriteAllText(@"E:\1.txt", sourceText);
        ////    File.WriteAllText(@"E:\2.txt", resultText);
        ////    File.WriteAllText(@"E:\3.txt", generatedCode);
        ////}

        ////Assert.AreEqual(sourceText, resultText);
    }
Ejemplo n.º 34
0
 public override string Generate(AlterSchemaExpression expression)
 {
     return(string.Format("ALTER TABLE {0}.{1} SET SCHEMA {2}", Quoter.QuoteSchemaName(expression.SourceSchemaName), Quoter.QuoteTableName(expression.TableName), Quoter.QuoteSchemaName(expression.DestinationSchemaName)));
 }
Ejemplo n.º 35
0
        public override string Generate(UpdateDataExpression expression)
        {
            var updateItems  = new List <string>();
            var whereClauses = new List <string>();

            foreach (var item in expression.Set)
            {
                updateItems.Add(string.Format("{0} = {1}", Quoter.QuoteColumnName(item.Key), Quoter.QuoteValue(item.Value)));
            }

            if (expression.IsAllRows)
            {
                whereClauses.Add("1 = 1");
            }
            else
            {
                foreach (var item in expression.Where)
                {
                    whereClauses.Add(string.Format("{0} {1} {2}", Quoter.QuoteColumnName(item.Key),
                                                   item.Value == null ? "IS" : "=", Quoter.QuoteValue(item.Value)));
                }
            }
            return(String.Format("UPDATE {0}.{1} SET {2} WHERE {3}", Quoter.QuoteSchemaName(expression.SchemaName), Quoter.QuoteTableName(expression.TableName), String.Join(", ", updateItems.ToArray()), String.Join(" AND ", whereClauses.ToArray())));
        }
Ejemplo n.º 36
0
 public override string Generate(DeleteColumnExpression expression)
 {
     return(String.Format(DropColumn, Quoter.QuoteTableName(expression.TableName), Quoter.QuoteColumnName(expression.ColumnName)));
 }
Ejemplo n.º 37
0
    private void Test(
        string sourceText,
        string expected,
        bool useDefaultFormatting = true,
        bool removeRedundantModifyingCalls = true,
        bool shortenCodeWithUsingStatic = false)
    {
        var quoter = new Quoter
        {
            UseDefaultFormatting = useDefaultFormatting,
            RemoveRedundantModifyingCalls = removeRedundantModifyingCalls,
            ShortenCodeWithUsingStatic = shortenCodeWithUsingStatic
        };
        var actual = quoter.Quote(sourceText);
        Assert.AreEqual(expected, actual);

        Test(sourceText);
    }
Ejemplo n.º 38
0
 public override string Generate(DeleteSchemaExpression expression)
 {
     return(string.Format("DROP SCHEMA {0}", Quoter.QuoteSchemaName(expression.SchemaName)));
 }