예제 #1
0
        /**
         * Call this to generate a log from a template.
         * @param sev: The severity of the message
         * @param key: The keyword which maps to the template
         * @param args: A variable number of string arguments
         */
        public void FormattedLog(string sev, string key, params string[] args)
        {
            FormattableString str = FormattableStringFactory
                                    .Create(KeyToLog[key], args);

            RawLog(sev, string.Format(str.Format, args));
        }
예제 #2
0
        public static FormattableString Join(string separator, IEnumerable <FormattableString> strings)
        {
            StringBuilder            sb   = new StringBuilder();
            List <FormattableString> fmts = new List <FormattableString>();
            int id = 0;

            using var enumerator = strings.GetEnumerator();

            if (!enumerator.MoveNext())
            {
                return($"");
            }

            if (enumerator.Current != null)
            {
                sb.Append($"{{{id}}}");
                fmts.Add(enumerator.Current);
                id++;
            }

            while (enumerator.MoveNext())
            {
                sb.Append(separator);

                if (enumerator.Current != null)
                {
                    sb.Append($"{{{id}}}");
                    fmts.Add(enumerator.Current);
                    id++;
                }
            }

            return(FormattableStringFactory.Create(sb.ToString(), fmts.ToArray()));
        }
예제 #3
0
        private static FormattableString CreateQueryWithConditions(UniversityFilterInSql filter)
        {
            string sqlQuery;

            if (filter.ComplexQuery)
            {
                sqlQuery = @$ "SELECT
                    {filter.SelectedFieldsForSql}
                    {(!string.IsNullOrWhiteSpace(filter.Region) ? filter.RegionConditionForSqlInnerJoinApproach : string.Empty)} 
                    UNION
                    SELECT
                    {filter.SelectedFieldsForSql}
                    {filter.Where} 
                    {(!string.IsNullOrWhiteSpace(filter.SearchText) ? filter.SearchTextConditionForSql : string.Empty)}
                    {(filter.IsGoverment != null ? filter.GovermentConditionForSql : string.Empty)}";
            }
            else
            {
                sqlQuery = @$ "SELECT
                    {filter.SelectedFieldsForSql}
                    {(!string.IsNullOrWhiteSpace(filter.Region) ? filter.RegionConditionForSqlInnerJoinApproach : string.Empty)}        
                    {filter.Where} 
                    {(!string.IsNullOrWhiteSpace(filter.SearchText) ? filter.SearchTextConditionForSql : string.Empty)}
                    {(filter.IsGoverment != null ? filter.GovermentConditionForSql : string.Empty)}";
            }

            var parametersData = filter.GetParametersSequence();

            for (int index = 0; index < parametersData.Count; index++)
            {
                sqlQuery = sqlQuery.Replace(parametersData.ElementAt(index).Key, index.ToString());
            }

            return(FormattableStringFactory.Create(sqlQuery, parametersData.Values.ToArray()));
        }
예제 #4
0
        public FormattableString Build(IDapperCommandBuilder commandBuilder)
        {
            FormattableString expression = notExpression
                                           .Criterion
                                           .GetExpressionBuilder()
                                           .Build(commandBuilder);

            string commandTemplate = expression.Format;
            string notOperator     = notExpression.Criterion.GetNotOperator();

            var match = Regex.Match(commandTemplate, "(Between|Like|In|Null|=)");

            if (match.Success)
            {
                commandTemplate = Regex.Replace(
                    input: commandTemplate,
                    pattern: match.Value,
                    replacement: $"{notOperator}{match.Value}",
                    options: RegexOptions.IgnoreCase);
            }

            return(FormattableStringFactory.Create(
                       commandTemplate,
                       expression.GetArguments()));
        }
예제 #5
0
        /// <summary>
        /// Creates a formattable string from this parameterized SQL.
        /// </summary>
        /// <returns></returns>
        public FormattableString ToFormattableString()
        {
            var r = new Regex(@"@[A-Z_][A-Z0-9_]+", RegexOptions.IgnoreCase);

            var list = new List <object>();
            var fmt  = r.Replace(
                SqlText, (m) =>
            {
                var placeholder = $"{{{list.Count}}}";
                if (ParameterValues.ContainsKey(m.Value))
                {
                    list.Add(ParameterValues[m.Value]);
                    return(placeholder);
                }

                if (ParameterValues.ContainsKey(m.Value.Substring(1)))
                {
                    list.Add(ParameterValues[m.Value.Substring(1)]);
                    return(placeholder);
                }

                return(m.Value);
            }
                );

            return(FormattableStringFactory.Create(fmt, list.ToArray()));
        }
예제 #6
0
        public FormattableString Build()
        {
            IEnumerable <object?> allArgs = formattableStrings.SelectMany(f => f.GetArguments());
            string joinedFormats          = string.Join("", formattableStrings.Select(x => x.Format));

            return(FormattableStringFactory.Create(joinedFormats, allArgs.ToArray()));
        }
예제 #7
0
        public override InteractResult OnActRight(InteractionContext context)
        {
            if (this.wantedItem == string.Empty)
            {
                this.wantedItem = SearchAndSelectItemSets.DiscoveredItems.Items.Shuffle().First().FriendlyName;
            }

            var itemStack = context.Player.User.Inventory.NonEmptyStacks.Where(stack => stack.Item.FriendlyName == this.wantedItem).FirstOrDefault();

            if (itemStack != null)
            {
                var gift   = AllItems.Where(x => !(x is Skill) && x.Group != "Actionbar Items").Shuffle().First();
                var result = context.Player.User.Inventory.TryModify(changeSet =>
                {
                    changeSet.RemoveItem(itemStack.Item.Type);
                    changeSet.AddItem(gift.Type);
                }, context.Player.User);

                if (result.Success)
                {
                    context.Player.SendTemporaryMessage(FormattableStringFactory.Create("Ecko accepts your tribute of {0:wanted} and grants you {1:given} for your devotion.", this.wantedItem, gift.FriendlyName));
                    this.wantedItem = SearchAndSelectItemSets.DiscoveredItems.Items.Shuffle().First().FriendlyName;
                }
            }
            else
            {
                context.Player.SendTemporaryMessage(FormattableStringFactory.Create("Ecko demands {0:wanted}!", this.wantedItem));
            }

            return(InteractResult.Success);
        }
예제 #8
0
        /// <summary>
        /// Compare the list of tuples with the properties of the file version
        /// </summary>
        /// <param name="files">The files.</param>
        /// <param name="propertyAndConditions">The property and conditions.</param>
        /// <exception cref="ArgumentException">propertyAndConditions - Invalid comparator for {propertyAndCondition.Item1} with value {propertyAndCondition.Item3}</exception>
        public static IQueryable <File> CompareFileProperties(this DbSet <File> files, List <Tuple <string, char, string> > propertyAndConditions)
        {
            foreach (var propertyAndCondition in propertyAndConditions)
            {
                char comparator = propertyAndCondition.Item2;
                // Check if the comparator is a valid one (as in, in the comparator enum)
                if (!Enum.IsDefined(typeof(Comparators), comparator))
                {
                    throw new ArgumentException(nameof(propertyAndConditions), $"Invalid comparator for {propertyAndCondition.Item1} with value {propertyAndCondition.Item3}");
                }


                var command = $"SELECT * FROM dbo.Files WHERE Id = (SELECT FileId FROM dbo.FileProperties WHERE Name = {propertyAndCondition.Item1} AND Value ";

                if (comparator != (char)Comparators.Different)
                {
                    command += $"{comparator}";
                }
                else
                {
                    command += "<>";
                }

                command += $" {comparator}";

                files.FromSqlInterpolated(FormattableStringFactory.Create(command));
            }
            return(files);
        }
예제 #9
0
        public void Cleanup(string fileName, DokanFileInfo info)
        {
            if (info.Context != null)
            {
                Console.WriteLine(FormatProviders.DokanFormat(FormattableStringFactory.Create("{0}('{1}', {2} - entering", (object)nameof(Cleanup), (object)fileName, (object)info)));
            }
            FileStream context = info.Context as FileStream;

            if (context != null)
            {
                // ISSUE: explicit non-virtual call
                __nonvirtual(context.Dispose());
            }
            info.Context = (object)null;
            if (info.DeleteOnClose)
            {
                if (info.IsDirectory)
                {
                    Directory.Delete(this.method_0(fileName));
                }
                else
                {
                    File.Delete(this.method_0(fileName));
                }
            }
            long num = (long)this.method_1(nameof(Cleanup), fileName, info, NtStatus.Success);
        }
예제 #10
0
        public void GetArgumentWorks()
        {
            var s = FormattableStringFactory.Create("x = {0}, y = {1}", "x", "y");

            Assert.AreEqual("x", s.GetArgument(0), "0");
            Assert.AreEqual("y", s.GetArgument(1), "1");
        }
        private static void FetchWhitelist(string url, Action <List <string>, Exception> callback)
        {
            List <string> result = null;

            ThreadPool.QueueUserWorkItem(ar =>
            {
                Exception exception = null;
                try
                {
                    var webRequest     = WebRequest.Create(url);
                    webRequest.Timeout = 10000;
                    using (var response = webRequest.GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            using (var streamReader = new StreamReader(responseStream))
                                result = new List <string>(streamReader
                                                           .ReadToEnd()
                                                           .Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteErrorLine(Localizer.Do(FormattableStringFactory.Create("{0} Error when fetching whitelist: {1} {2}", LogTag, url, (object)ex.Message)));
                    exception = ex;
                }
                callback(result, exception);
            });
        }
예제 #12
0
        public void ToStringWithFormatProviderWorks_SPI_1651()
        {
            var s = FormattableStringFactory.Create("x = {0}, y = {0:FMT}", new MyFormattable());

            // #1651
            Assert.AreEqual("x = Formatted: MyFormatProvider, y = Formatted: FMT, MyFormatProvider", s.ToString(new MyFormatProvider()));
        }
예제 #13
0
        public void IFormattableToStringWorks_SPI_1633_1651()
        {
            IFormattable s = FormattableStringFactory.Create("x = {0}, y = {0:FMT}", new MyFormattable());

            // #1633
            // #1651
            Assert.AreEqual("x = Formatted: MyFormatProvider, y = Formatted: FMT, MyFormatProvider", s.ToString(null, new MyFormatProvider()));
        }
예제 #14
0
 public void FormattableStringFactory_IsRenderedAsInterpolation()
 {
     Assert.Equal(
         @"() => Interpolation($""abc"")",
         ExpressionToCode.ToCode(
             () => Interpolation(FormattableStringFactory.Create("abc", new object[] { }))
             ));
 }
예제 #15
0
        public void GetArgumentsWorks()
        {
            var s    = FormattableStringFactory.Create("x = {0}, y = {1}", "x", "y");
            var args = s.GetArguments();

            Assert.AreEqual("x", args[0], "0");
            Assert.AreEqual("y", args[1], "1");
        }
예제 #16
0
        public FormattableString Build(IDapperCommandBuilder commandBuilder)
        {
            var expressions    = BuildExpressions(commandBuilder);
            var junctionFormat = $"({BuildFormat(expressions)})";

            return(FormattableStringFactory.Create(
                       junctionFormat,
                       expressions.ToArray()));
        }
        public FormattableString ToFormattableString()
        {
            var format = this.buffer.ToString();
            var args   = this.arguments.ToArray();

            var result = FormattableStringFactory.Create(format, args);

            return(result);
        }
예제 #18
0
        public void ArgumentCountWorks()
        {
            var s1 = FormattableStringFactory.Create("{0}", "x");

            Assert.AreEqual(1, s1.ArgumentCount, "#1");
            var s2 = FormattableStringFactory.Create("{0}, {1}", "x", "y");

            Assert.AreEqual(2, s2.ArgumentCount, "#2");
        }
예제 #19
0
        /// <summary>
        /// 解析模板表达式,创建参数化查询对象
        /// </summary>
        /// <param name="text">查询文本</param>
        /// <returns>参数化查询</returns>
        public static ParameterizedQuery Text(string text)
        {
            if (text == null)
            {
                return(null);
            }

            return(Db.ServiceProvider.GetService <ITemplateParser>().ParseTemplate(FormattableStringFactory.Create(text)));
        }
예제 #20
0
        public void FormattableStringTest()
        {
            var now         = DateTime.Now;
            var formattable = FormattableStringFactory.Create("Hello NStandard. ({0})", now);

            Assert.AreEqual($"Hello NStandard. ({now})", formattable.ToString());

            DateTimeOffset.Now.ToUnixTimeSeconds();
        }
예제 #21
0
        /// <summary>
        /// 解析模板表达式,创建参数化查询对象
        /// </summary>
        /// <param name="text">查询文本</param>
        /// <returns>参数化查询</returns>
        public static ParameterizedQuery Text(string text)
        {
            if (text == null)
            {
                return(null);
            }

            return(ParameterizedQueryService.GetTemplateParser().ParseTemplate(FormattableStringFactory.Create(text)));
        }
예제 #22
0
파일: TNT.T.cs 프로젝트: theolivenbaum/tnt
        public static string t(FormattableString formattable)
        {
            var translatedFormattableString =
                Translations.TryGetValue(formattable.Format, out var translated)
                    ? FormattableStringFactory.Create(translated, formattable.GetArguments())
                    : formattable;

            return(translatedFormattableString.ToString());
        }
        public FormattableString Build(IDapperCommandBuilder commandBuilder)
        {
            string       commandTemplate = nullExpression.GetCommandTemplate();
            IFormattable columnName      = Sql.Column(nullExpression.GetPropertyName());

            return(FormattableStringFactory.Create(
                       commandTemplate,
                       columnName));
        }
 public void FormattableStringFactory_NonConstantStringIsNoInterpolation()
 {
     var s = "abc";
     Assert.Equal(
         @"() => Interpolation(FormattableStringFactory.Create(s, new object[] { }))",
         ExpressionToCode.ToCode(
             () => Interpolation(FormattableStringFactory.Create(s))
         ));
 }
        public void FormattableStringFactory_NonInlineArrayIsNoInterpolation()
        {
            var arr = new object[0];

            Assert.Equal(
                @"() => Interpolation(FormattableStringFactory.Create(""abc"", arr))",
                ExpressionToCode.ToCode(
                    () => Interpolation(FormattableStringFactory.Create("abc", arr))
                ));
        }
예제 #26
0
        private NtStatus method_1(string string_1, string string_2, DokanFileInfo dokanFileInfo_0, NtStatus ntStatus_0, params object[] object_0_1)
        {
            string str = object_0_1 == null || object_0_1.Length == 0 ? string.Empty : ", " + string.Join(", ", ((IEnumerable <object>)object_0_1).Select <object, string>((Func <object, string>)(object_0_2 => string.Format((IFormatProvider)FormatProviders.DefaultFormatProvider, "{0}", new object[1]
            {
                object_0_2
            }))));

            this.consoleLogger_0.Debug(FormatProviders.DokanFormat(FormattableStringFactory.Create("{0}('{1}', {2}{3}) -> {4}", (object)string_1, (object)string_2, (object)dokanFileInfo_0, (object)str, (object)ntStatus_0)));
            return(ntStatus_0);
        }
예제 #27
0
 private bool RequestCancellation(int id)
 {
     using (var context = TaskRunnerEntities.Get(_customer))
     {
         var sql          = ($@"UPDATE tasks SET {_isCancellationRequested} = {{0}} WHERE id = {{1}} AND {_stateId}={{2}}");
         var fString      = FormattableStringFactory.Create(sql, _getIsCancellationRequestedValue(true), id, State.Running);
         var rowsAffected = context.Database.ExecuteSqlInterpolated(fString);
         return(rowsAffected == 1);
     }
 }
예제 #28
0
        /// <summary>
        /// Get temporal data
        /// </summary>
        /// <typeparam name="T">Entity type</typeparam>
        /// <param name="dbSet">Data set</param>
        /// <param name="temporalCriteria">Temporal criteria of the SQL query</param>
        /// <param name="arguments">Temporal SQL arguments</param>
        /// <returns>Temporal data</returns>
        private static IQueryable <T> AsTemporal <T>(this DbSet <T> dbSet, string temporalCriteria, params object[] arguments) where T : class
        {
            var table = dbSet
                        .GetService <ICurrentDbContext>()
                        .GetTableName <T>();
            var selectSql = $"SELECT * FROM {table}";
            var sql       = FormattableStringFactory.Create(selectSql + " FOR SYSTEM_TIME " + temporalCriteria, arguments);

            return(dbSet.FromSqlInterpolated(sql));
        }
예제 #29
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));
            }
        }
예제 #30
0
        public DapperCommand Build()
        {
            var expressions    = BuildExpressions(this);
            var junctionFormat = BuildFormat(expressions);

            FormattableString command = FormattableStringFactory.Create(
                junctionFormat,
                expressions.ToArray());

            return(new DapperCommand(command, values));
        }