Exemplo n.º 1
0
        public static void TestBasic()
        {
            var p = new Person();

            Assert.AreEqual("Jane is 10 year{s} old", $"{p.Name} is {p.Age} year{{s}} old");
            Assert.AreEqual("                Jane is 010 year{s} old", $"{p.Name,20} is {p.Age:D3} year{{s}} old");

            Assert.AreEqual("Jane is 10 years old", $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old");
            p.Age = 1;
            Assert.AreEqual("Jane is 1 year old", $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old");

            int i = 0, j = 1, k = 2;

            Assert.AreEqual("i = 0, j = 1", $"i = {i}, j = {j}");
            Assert.AreEqual("{0, 1}", $"{{{i}, {j}}}");
            Assert.AreEqual("i = 00, j = 1, k =            2", $"i = {i:00}, j = {j:##}, k = {k,12:#0}");
            Assert.AreEqual("0, 0, 0", $"{F1()}, {P = F2()}, {F3()}");

            IFormattable      f1 = $"i = {i}, j = {j}";
            FormattableString f2 = $"i = {i}, j = {j}";

            Assert.AreEqual(2, f2.ArgumentCount);
            Assert.AreEqual("i = {0}, j = {1}", f2.Format);
            Assert.AreEqual(0, f2.GetArgument(0));
            Assert.AreEqual(1, f2.GetArgument(1));
            Assert.AreEqual(2, f2.GetArguments().Length);
            Assert.AreEqual("i = 0, j = 1", f2.ToString());
        }
Exemplo n.º 2
0
        private static string Format(FormattableString s)
        {
            switch (s.ArgumentCount)
            {
            case 0:
                return(s.Format);

            case 1:
                return(string.Format(s.Format, Format(s.GetArgument(0))));

            case 2:
                return(string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1))));

            case 3:
                return(string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)), Format(s.GetArgument(2))));

            default:
                object[] args          = s.GetArguments();
                object[] formattedArgs = new object[args.Length];
                for (int i = 0; i < args.Length; i++)
                {
                    formattedArgs[i] = Format(args[i]);
                }
                return(string.Format(s.Format, formattedArgs));
            }
        }
Exemplo n.º 3
0
        public void TestReplacement4()
        {
            FormattableString formattableString = TestFormat4.FormattableWith(new { Replacement1 = Replacement1, Replacement2 = Replacement2 });

            Assert.Equal(TestFormat4Composite, formattableString.Format);
            Assert.Equal(2, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));
            Assert.Equal(Replacement2, formattableString.GetArgument(1));
            Assert.Equal(TestFormat4Solution, formattableString.ToString());
        }
Exemplo n.º 4
0
        private static ParameterFactoryFuncFormattableString GetFactory(FormattableString commandString)
        {
            if (ParameterFactoryCache.TryGet(commandString.Format, out var cachedFactory))
            {
                return(cachedFactory);
            }

            var context = GetContext();

            var factoryBodyExpressions = new List <Expression>();

            var commandStringParamExpr = Expression.Parameter(typeof(FormattableString), "commandString");

            var names = Enumerable.Range(0, commandString.ArgumentCount)
                        .Select(x => $"@p__blazer__{x}")
                        .ToArray();

            var formattedCommandText  = string.Format(commandString.Format, names);
            var commandTextAssignExpr = Expression.Assign(
                Expression.Property(context.CommandExpr, context.CommandCommandTextProperty),
                Expression.Constant(formattedCommandText));

            factoryBodyExpressions.Add(commandTextAssignExpr);

            var namesVarExpr    = Expression.Variable(typeof(string[]), "names");
            var namesAssignExpr = Expression.Assign(
                namesVarExpr,
                Expression.Constant(names));

            factoryBodyExpressions.Add(namesAssignExpr);

            var getArgumentMethod = typeof(FormattableString).GetMethod(nameof(FormattableString.GetArgument), FLAGS_PUBINST);

            for (int i = 0; i < commandString.ArgumentCount; i++)
            {
                var paramValueExpr = Expression.Call(
                    commandStringParamExpr,
                    getArgumentMethod,
                    Expression.Constant(i));

                var parameterValue = new ParameterExpressionFactory.ParameterValue
                {
                    Name      = names[i],
                    ValueExpr = paramValueExpr,
                    ValueType = commandString.GetArgument(i).GetType()
                };

                factoryBodyExpressions.Add(ParameterExpressionFactory.GetExpression(context, parameterValue));
            }

            var lambdaBlockExpr = Expression.Block(
                new[] { namesVarExpr },
                factoryBodyExpressions);
            var lambdaExpr = Expression.Lambda <ParameterFactoryFuncFormattableString>(lambdaBlockExpr, context.CommandExpr, commandStringParamExpr);
            var lambda     = lambdaExpr.Compile();

            ParameterFactoryCache.Add(commandString.Format, lambda);

            return(lambda);
        }
Exemplo n.º 5
0
        public static IQueryable <T> SqlQueryInterpolated <T>(this DatabaseFacade facade, FormattableString sql) where T : class, new()
        {
            var conn = facade.GetDbConnection();

            conn.Open();
            var cmd        = conn.CreateCommand();
            var parameters = new List <SqlParameter>();
            var arguments  = new List <string>();

            for (int i = 0; i < sql.ArgumentCount; i++)
            {
                parameters.Add(new SqlParameter($"@arg{i}", sql.GetArgument(i)));
                arguments.Add($"@arg{i}");
            }
            ;
            cmd.CommandText = string.Format(sql.Format, arguments.ToArray());
            cmd.Parameters.AddRange(parameters.ToArray());
            var reader = cmd.ExecuteReader();
            var dt     = new DataTable();

            dt.Load(reader);
            reader.Close();
            conn.Close();
            return(dt.ToModels <T>().AsQueryable());
        }
Exemplo n.º 6
0
        public ConcreteSyntaxTree Format(FormattableString input)
        {
            var anchorValues = new List <ConcreteSyntaxTree>();
            // Because template strings are difficult to process, we use the existing string.Format to do the processing
            // and we insert anchors to identify where the ConcreteSyntaxTree values are.
            // Template string processing logic can be found here: https://github.com/dotnet/runtime/blob/ae5ee8f02d6fc99469e1f194be45b5f649c2da1a/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs#L60
            var formatArguments = Enumerable.Range(0, input.ArgumentCount).
                                  Select(index => {
                object argument = input.GetArgument(index) !;
                if (argument is ConcreteSyntaxTree treeArg)
                {
                    anchorValues.Add(treeArg);
                    return($"{anchorUUID}{anchorValues.Count - 1}");
                }

                return(argument);
            }).ToArray();

            var anchorString = string.Format(input.Format, formatArguments);

            for (int argIndex = 0; argIndex < anchorValues.Count; argIndex++)
            {
                var split = anchorString.Split($"{anchorUUID}{argIndex}");
                anchorString = split.Length > 1 ? split[1] : "";
                Write(split[0]);
                Append(anchorValues[argIndex]);
            }
            if (anchorString != "")
            {
                Write(anchorString);
            }

            return(this);
        }
Exemplo n.º 7
0
 static void ExploreFormattableStr(FormattableString s)
 {
     Debug.Log(s.ToString());
     Debug.Log(s.Format);
     Debug.Log(s.ArgumentCount);
     Debug.Log(s.GetArgument(0));
 }
Exemplo n.º 8
0
        internal static string FormatUrl(FormattableString formattable, out ulong guildId, out ulong channelId, out ulong webhookId)
        {
            var raw = formattable.Format;

            guildId   = 0;
            channelId = 0;
            webhookId = 0;

            if (formattable.ArgumentCount == 0)
            {
                return(raw);
            }

            var builder = new StringBuilder(raw.Length);
            var rawSpan = raw.AsSpan();
            int firstBracketIndex;

            while ((firstBracketIndex = rawSpan.IndexOf('{')) != -1)
            {
                builder.Append(rawSpan.Slice(0, firstBracketIndex));
                rawSpan = rawSpan.Slice(firstBracketIndex + 1);
                var secondBracketIndex = rawSpan.IndexOf('}');
                var segment            = rawSpan.Slice(0, secondBracketIndex);
                int argumentIndex      = segment[0] - '0';
                var argument           = formattable.GetArgument(argumentIndex);
                builder.Append(argument);
                if (segment.Length > 1)
                {
                    var nameSpan = segment.Slice(2);
                    if (nameSpan.Equals("guild_id", StringComparison.Ordinal))
                    {
                        guildId = Convert.ToUInt64(argument);
                    }

                    else if (nameSpan.Equals("channel_id", StringComparison.Ordinal))
                    {
                        channelId = Convert.ToUInt64(argument);
                    }

                    else if (nameSpan.Equals("webhook_id", StringComparison.Ordinal))
                    {
                        webhookId = Convert.ToUInt64(argument);
                    }

                    else
                    {
                        throw new ArgumentException($"Unrecognized url name '{nameSpan.ToString()}'.", nameof(formattable));
                    }
                }

                rawSpan = rawSpan.Slice(secondBracketIndex + 1);
            }

            if (rawSpan.Length > 0)
            {
                builder.Append(rawSpan);
            }

            return(builder.ToString());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Create a Kusto query from an interpolated string.  The interpolated values will be quoted and escaped as necessary.
        /// </summary>
        /// <param name="filter">An interpolated query string.</param>
        /// <returns>A valid Kusto query.</returns>
        public static string CreateQuery(FormattableString filter)
        {
            if (filter == null)
            {
                return(null);
            }

            string[] args = new string[filter.ArgumentCount];
            for (int i = 0; i < filter.ArgumentCount; i++)
            {
                args[i] = filter.GetArgument(i) switch
                {
                    // Null
                    null => throw new ArgumentException(
                              $"Unable to convert argument {i} to an Kusto literal. " +
                              $"Unable to format an untyped null value, please use typed-null expression " +
                              $"(bool(null), datetime(null), dynamic(null), guid(null), int(null), long(null), real(null), double(null), time(null))"),

                          // Boolean
                          true => "true",
                          false => "false",

                          // Numeric
                          sbyte x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
                          byte x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
                          short x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
                          ushort x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
                          int x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
                          uint x => $"int({x.ToString(CultureInfo.InvariantCulture)})",

                          float x => $"real({x.ToString(CultureInfo.InvariantCulture)})",
                          double x => $"real({x.ToString(CultureInfo.InvariantCulture)})",

                          // Int64
                          long x => $"long({x.ToString(CultureInfo.InvariantCulture)})",
                          ulong x => $"long({x.ToString(CultureInfo.InvariantCulture)})",

                          decimal x => $"decimal({x.ToString(CultureInfo.InvariantCulture)})",

                          // Guid
                          Guid x => $"guid({x.ToString("D", CultureInfo.InvariantCulture)})",

                          // Dates as 8601 with a time zone
                          DateTimeOffset x => $"datetime({x.UtcDateTime.ToString("O", CultureInfo.InvariantCulture)})",
                          DateTime x => $"datetime({x.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)})",
                          TimeSpan x => $"time({x.ToString("c", CultureInfo.InvariantCulture)})",

                          // Text
                          string x => EscapeStringValue(x),
                          char x => EscapeStringValue(x),

                          // Everything else
                          object x => throw new ArgumentException(
                                    $"Unable to convert argument {i} from type {x.GetType()} to an Kusto literal.")
                };
            }

            return(string.Format(CultureInfo.InvariantCulture, filter.Format, args));
        }
Exemplo n.º 10
0
 internal static void ReleaseUnused(FormattableString str)
 {
     for (var i = 0; i < str.ArgumentCount; i++)
     {
         var reusable = str.GetArgument(i) as IReusable;
         reusable?.Release();
     }
 }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            int value = 5;
            FormattableString formattable = $"value={value}";

            Console.WriteLine(formattable.Format);
            Console.WriteLine(formattable.GetArgument(0));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Create an OData filter expression from an interpolated string.  The interpolated values will be quoted and escaped as necessary.
        /// </summary>
        /// <param name="filter">An interpolated filter string.</param>
        /// <returns>A valid OData filter expression.</returns>
        public static string Create(FormattableString filter)
        {
            if (filter == null)
            {
                return(null);
            }

            string[] args = new string[filter.ArgumentCount];
            for (int i = 0; i < filter.ArgumentCount; i++)
            {
                args[i] = filter.GetArgument(i) switch
                {
                    // Null
                    null => "null",

                    // Boolean
                    bool x => x.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(),

                    // Numeric
                    sbyte x => x.ToString(CultureInfo.InvariantCulture),
                    byte x => x.ToString(CultureInfo.InvariantCulture),
                    short x => x.ToString(CultureInfo.InvariantCulture),
                    ushort x => x.ToString(CultureInfo.InvariantCulture),
                    int x => x.ToString(CultureInfo.InvariantCulture),
                    uint x => x.ToString(CultureInfo.InvariantCulture),
                    decimal x => x.ToString(CultureInfo.InvariantCulture),
                    float x => x.ToString(CultureInfo.InvariantCulture),
                    double x => x.ToString(CultureInfo.InvariantCulture),

                    // Int64
                    long x => x.ToString(CultureInfo.InvariantCulture) + "L",
                    ulong x => x.ToString(CultureInfo.InvariantCulture) + "L",

                    // Guid
                    Guid x => $"{XmlConstants.LiteralPrefixGuid}'{x.ToString()}'",

                    // binary
                    byte[] x => $"X'{string.Join(string.Empty, x.Select(b => b.ToString("D2", CultureInfo.InvariantCulture)))}'",
                    BinaryData x => $"X'{string.Join(string.Empty, x.ToArray().Select(b => b.ToString("D2", CultureInfo.InvariantCulture)))}'",

                    // Dates as 8601 with a time zone
                    DateTimeOffset x => $"{XmlConstants.LiteralPrefixDateTime}'{XmlConvert.ToString(x.UtcDateTime, XmlDateTimeSerializationMode.RoundtripKind)}'",
                    DateTime x => $"{XmlConstants.LiteralPrefixDateTime}'{XmlConvert.ToString(x.ToUniversalTime(), XmlDateTimeSerializationMode.RoundtripKind)}'",

                    // Text
                    string x => $"'{x.Replace("'", "''")}'",
                    char x => $"'{x.ToString().Replace("'", "''")}'",
                    StringBuilder x => $"'{x.Replace("'", "''")}'",

                    // Everything else
                    object x => throw new ArgumentException(
                              $"Unable to convert argument {i} from type {x.GetType()} to an OData literal.")
                };
            }

            return(string.Format(CultureInfo.InvariantCulture, filter.Format, args));
        }
    }
Exemplo n.º 13
0
        //public static string Invariant(FormattableString s) =>
        //    s.ToString(CultureInfo.InvariantCulture);



        public static void ShowDetails(FormattableString s)
        {
            Console.WriteLine($"argument count: {s.ArgumentCount}");
            Console.WriteLine($"format: {s.Format}");
            for (int i = 0; i < s.ArgumentCount; i++)
            {
                Console.WriteLine($"Argument {i}: {s.GetArgument(i)}");
            }
        }
Exemplo n.º 14
0
        public void TestNestedProperties()
        {
            FormattableString formattableString = TestFormat5.FormattableWith(new { Foo = new { Replacement1 = Replacement1 } });

            Assert.Equal(TestFormat5Composite, formattableString.Format);
            Assert.Equal(1, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));
            Assert.Equal(TestFormat5Solution, formattableString.ToString());
        }
Exemplo n.º 15
0
        public void TestReplacement3()
        {
            FormattableString formattableString = TestFormat3.FormattableWith(new { Replacement1 = Replacement1 });

            Assert.Equal(TestFormat3Composite, formattableString.Format);
            Assert.Equal(1, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));
            Assert.Equal(TestFormat3Solution, formattableString.ToString());
        }
Exemplo n.º 16
0
        public static void MoreFormattableString()
        {
            int x = 3, y = 4;
            FormattableString s = $"The result of {x} + {y} is {x + y}";

            Console.WriteLine($"format: {s.Format}");
            for (int i = 0; i < s.ArgumentCount; i++)
            {
                Console.WriteLine($"argument {i}: {s.GetArgument(i)}");
            }
        }
Exemplo n.º 17
0
        public void StringPractice2()
        {
            int x = 3, y = 4;
            FormattableString string1 = $"X is {x}, Y is {y}, the addition is {x + y}";

            for (int i = 0; i < string1.ArgumentCount; i++)
            {
                Console.WriteLine($"the {i}th argument is {string1.GetArgument(i)}");
            }
            Console.WriteLine(string1);
        }
Exemplo n.º 18
0
        public void Create_ArgumentsMatchExpected(object[] arguments)
        {
            FormattableString fs = FormattableStringFactory.Create("", arguments);

            Assert.Same(arguments, fs.GetArguments());
            Assert.Equal(arguments.Length, fs.ArgumentCount);
            for (int i = 0; i < arguments.Length; i++)
            {
                Assert.Same(arguments[i], fs.GetArgument(i));
            }
        }
Exemplo n.º 19
0
        public void TestCustomBraces()
        {
            string            format            = "abc{{Replacement1}<Replacement2>";
            string            formatComposite   = "abc{{{{Replacement1}}{0}";
            string            formatSolution    = $"abc{{{{Replacement1}}{Replacement2}";
            FormattableString formattableString = format.FormattableWith(new { Replacement1 = Replacement1, Replacement2 = Replacement2 }, MissingKeyBehaviour.ThrowException, null, '<', '>');

            Assert.Equal(formatComposite, formattableString.Format);
            Assert.Equal(1, formattableString.ArgumentCount);
            Assert.Equal(Replacement2, formattableString.GetArgument(0));
            Assert.Equal(formatSolution, formattableString.ToString());
        }
Exemplo n.º 20
0
        public void TestFormatString()
        {
            FormattableString formattableString = TestFormat6.FormattableWith(new { Replacement1 = Replacement1 });

            Assert.Equal(TestFormat6Composite, formattableString.Format);
            Assert.Equal(1, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));

            var upperCaseFormatProvider = new UpperCaseFormatProvider();

            Assert.Equal(TestFormat6Solution, formattableString.ToString(upperCaseFormatProvider));
        }
Exemplo n.º 21
0
        public SqlStringBuilder Append(FormattableString data)
        {
            var s = data.Format;

            for (var i = 0; i < data.ArgumentCount; i++)
            {
                s = s.Replace("{" + i + "}", "@" + _pm.CurrentIndex);
                _pm.AddValues(data.GetArgument(i));
            }
            _sql.Append(s);
            return(this);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Create an OData filter expression from an interpolated string.  The
        /// interpolated values will be quoted and escaped as necessary.
        /// </summary>
        /// <param name="filter">An interpolated filter string.</param>
        /// <param name="formatProvider">
        /// Format provider used to convert values to strings.
        /// <see cref="CultureInfo.InvariantCulture"/> is used as a default.
        /// </param>
        /// <returns>A valid OData filter expression.</returns>
        public static string Create(FormattableString filter, IFormatProvider formatProvider)
        {
            if (filter == null)
            {
                return(null);
            }
            formatProvider ??= CultureInfo.InvariantCulture;

            string[] args = new string[filter.ArgumentCount];
            for (int i = 0; i < filter.ArgumentCount; i++)
            {
                args[i] = filter.GetArgument(i) switch
                {
                    // Null
                    null => "null",

                    // Boolean
                    bool x => x.ToString(formatProvider).ToLowerInvariant(),

                    // Numeric
                    sbyte x => x.ToString(formatProvider),
                    byte x => x.ToString(formatProvider),
                    short x => x.ToString(formatProvider),
                    ushort x => x.ToString(formatProvider),
                    int x => x.ToString(formatProvider),
                    uint x => x.ToString(formatProvider),
                    long x => x.ToString(formatProvider),
                    ulong x => x.ToString(formatProvider),
                    decimal x => x.ToString(formatProvider),

                    // Floating point
                    float x => JsonExtensions.Float(x, formatProvider),
                    double x => JsonExtensions.Double(x, formatProvider),

                    // Dates as 8601 with a time zone
                    DateTimeOffset x => JsonExtensions.Date(x, formatProvider),
                    DateTime x => JsonExtensions.Date(x, formatProvider),

                    // TODO: #10592- Unify on an Azure.Core spatial type

                    // Text
                    string x => Quote(x),
                    char x => Quote(x.ToString(formatProvider)),
                    StringBuilder x => Quote(x.ToString()),

                    // Everything else
                    object x => throw new ArgumentException(
                              $"Unable to convert argument {i} from type {x.GetType()} to an OData literal.")
                };
            }
            string text = string.Format(formatProvider, filter.Format, args);
            return(text);
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            int x = 3, y = 4;
            FormattableString s = $"{x} +{y}={x + y}"; //插值字符串

            WriteLine($"format:{s.Format}");           //得到格式字符串
            for (int i = 0; i < s.ArgumentCount; i++)
            {
                WriteLine($"argument{i}:{s.GetArgument(i)}");
            }

            var day             = DateTime.Now;

            WriteLine($"{day:d}");
            WriteLine($"{day:D}");
            WriteLine(FormattableString.Invariant($"{day:d}")); //不变的区域值
            WriteLine(FormattableString.Invariant($"{day:D}")); //不变的区域值
            WriteLine($"{day:yyyy-MM-dd HH:mm:ss}");            //MMM月份缩写

            double d = 3.1415926;

            WriteLine($"{d:###.###}"); //保留三位小数,#代表有值即显示值,无值就不显示;
            WriteLine($"{d:000.000}"); //也是保留三位小数,0代表有值就显示值,无值就显示0;



            //string pattern = @"\b(https?)(://)([.\w]+)([\s:]([\d]{2,4})?)\b";
            string pattern = @"\b(?<协议>https?)(://)(?<网址>[.\w]+)([\s:](?<端口>[\d]{2,4})?)\b";//?<groupname>

            /*
             * (https?)    ==>  http   https
             * (://)       ==> 如  ://
             * ([.\w]+)    ==>.或者任意字母数字字符  可以重复1或多次  如 www.  www.2.com
             * ([\s:]([\d]{2,4})?)
             * [\s:]     ==>任何空白字符  或 冒号:   如 :
             * ([\d]{2,4})? =>数字 至少出现2次但不超过4次 匹配0次或1次    如 80  8888
             */
            Regex           r   = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
            string          str = @"Hey,I've just found this amazing URI at
                        http:// what was it -oh yes https://www.wrox.com or http://www.wrox.com:80";
            MatchCollection mc  = r.Matches(str);

            foreach (Match item in mc)
            {
                WriteLine($"match:{item} in {item.Index}");
                foreach (var g in r.GetGroupNames())
                {
                    WriteLine($"match for {g}:{item.Groups[g].Value}");
                }
            }
            ReadKey();
        }
Exemplo n.º 24
0
        public void TestAsymmetricCustomBracesWithIgnore()
        {
            string format          = "abc{Replacement1>{DoesntExist>";
            string formatComposite = "abc{0}{{DoesntExist>";
            string formatSolution  = $"abc{Replacement1}{{DoesntExist>";

            FormattableString formattableString = format.FormattableWith(new { Replacement1 = Replacement1, Replacement2 = Replacement2 }, MissingKeyBehaviour.Ignore, null, '{', '>');

            Assert.Equal(formatComposite, formattableString.Format);
            Assert.Equal(1, formattableString.ArgumentCount);
            Assert.Equal(Replacement1, formattableString.GetArgument(0));
            Assert.Equal(formatSolution, formattableString.ToString());
        }
Exemplo n.º 25
0
        private static (string Sql, In[] Pars) Prepare(IDataClient client, FormattableString formattable)
        {
            var sql    = formattable.Format;
            var prefix = client.Dialect.ParameterPrefix;
            var pars   = new List <In>();

            for (var i = 0; i < formattable.ArgumentCount; i++)
            {
                var parName = prefix + "par" + i;
                sql = sql.Replace("{" + i + "}", parName);
                pars.Add(In.Named(parName, formattable.GetArgument(i)));
            }
            return(sql, pars.ToArray());
        }
Exemplo n.º 26
0
        public static int Parse(ref char[] buffer, FormattableString sql)
        {
            if (argBuffer == null)
            {
                argBuffer = new char[10];
            }

            var s           = sql.Format;
            var i           = 0;
            var index       = 0;
            var end         = s.Length;
            var finalLength = s.Length;

            EnsureCapacity(ref buffer, finalLength);
            while (i < end)
            {
                if (s[i] == '{')
                {
                    if (s[i + 1] == '{')
                    {
                        buffer[index++] = '{';
                        i += 2;
                    }
                    else
                    {
                        i++;
                        var argCount = 0;
                        while (s[i] != '}')
                        {
                            argBuffer[argCount++] = s[i++];
                        }
                        var argIndex = FormatArgumentToInt32(argBuffer, argCount);
                        var argValue = sql.GetArgument(argIndex);
                        WriteParameter(ref buffer, ref index, argValue, ref finalLength);
                        i++;
                    }
                }
                else
                {
                    buffer[index++] = s[i++];
                }
            }

            return(index);
        }
Exemplo n.º 27
0
        public static async Task SendKeyboardInput(this IVisualElement element, FormattableString input)
        {
            var    placeholder = Guid.NewGuid().ToString("N");
            string formatted   = string.Format(input.Format, Enumerable.Repeat(placeholder, input.ArgumentCount).Cast <object>().ToArray());

            string[] textParts = formatted.Split(placeholder);

            var inputs        = new List <IInput>();
            int argumentIndex = 0;

            foreach (string?part in textParts)
            {
                if (!string.IsNullOrEmpty(part))
                {
                    inputs.Add(new TextInput(part));
                }
                if (argumentIndex < input.ArgumentCount)
                {
                    object?argument = input.GetArgument(argumentIndex++);
                    switch (argument)
                    {
                    case Key key:
                        inputs.Add(new KeysInput(key));
                        break;

                    case IEnumerable <Key> keys:
                        inputs.Add(new KeysInput(keys));
                        break;

                    default:
                        string?stringArgument = argument?.ToString();
                        if (!string.IsNullOrEmpty(stringArgument))
                        {
                            inputs.Add(new TextInput(stringArgument));
                        }
                        break;
                    }
                }
            }
            await element.SendInput(new KeyboardInput(inputs.ToArray()));
        }
Exemplo n.º 28
0
    public static IDbCommand CreateCommand(this IDbConnection connection, FormattableString commandText)
    {
        var command = connection.CreateCommand();

        command.CommandType = CommandType.Text;
        if (commandText.ArgumentCount > 0)
        {
            var commandTextArguments = new string[commandText.ArgumentCount];
            for (var i = 0; i < commandText.ArgumentCount; i++)
            {
                commandTextArguments[i] = "@p" + i.ToString();
                command.AddParameter(commandTextArguments[i], commandText.GetArgument(i));
            }
            command.CommandText = string.Format(CultureInfo.InvariantCulture, commandText.Format, commandTextArguments);
        }
        else
        {
            command.CommandText = commandText.Format;
        }
        return(command);
    }
Exemplo n.º 29
0
        /// <summary>
        /// Map a string to a series of key presses that would type that string.
        /// If the string contains a sequence like ~Enter~ or ~Tab~ it is mapped to that key.
        /// e.g. maps "Consol{Control}{C}" to ['C', 'o', 'n', 's', 'o', 'l', ModifierKeys.Control, Key.C ]
        /// </summary>
        private IEnumerable <object> ConvertToKeys(FormattableString input)
        {
            for (int i = 0; i < input.Format.Length; i++)
            {
                var ch = input.Format[i]; // Format is a string with placeholders like "Console{0}{1}"

                if (ch == '{' &&
                    i + 2 < input.Format.Length &&
                    char.IsDigit(input.Format[i + 1]) &&
                    input.Format[i + 2] == '}')
                {
                    yield return(input.GetArgument((int)char.GetNumericValue(input.Format[i + 1])));

                    i += 2;
                }
                else
                {
                    yield return(ch);
                }
            }
        }
Exemplo n.º 30
0
        //This methods does something horrible...
        public void PrepareQuery(FormattableString query)
        {
            this.Command.Parameters.Clear();

            object[] @params = ArrayPool <object> .Shared.Rent(query.ArgumentCount);

            try
            {
                for (int i = 0; i < query.ArgumentCount; i++)
                {
                    object argument = query.GetArgument(i);
                    if (argument is ushort @short)
                    {
                        argument = Convert.ToInt32(@short);
                    }
                    else if (argument is uint @uint)
                    {
                        argument = Convert.ToInt64(@uint);
                    }
                    else if (argument is ulong @ulong)
                    {
                        argument = Unsafe.As <ulong, long>(ref @ulong);
                    }
                    else if (argument is uint[] uintArray)
                    {
                        argument = MemoryMarshal.Cast <uint, int>(uintArray).ToArray();
                    }

                    this.Command.Parameters.AddWithValue(i.ToString(), argument);

                    @params[i] = "@" + i;
                }

                this.SetQuery(string.Format(DatabaseIFormatProvider.Instance, query.Format, @params));
            }
            finally
            {
                ArrayPool <object> .Shared.Return(@params);
            }
        }