/** * 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)); }
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())); }
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())); }
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())); }
/// <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())); }
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())); }
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); }
/// <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); }
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); }
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); }); }
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())); }
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())); }
public void FormattableStringFactory_IsRenderedAsInterpolation() { Assert.Equal( @"() => Interpolation($""abc"")", ExpressionToCode.ToCode( () => Interpolation(FormattableStringFactory.Create("abc", new object[] { })) )); }
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"); }
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); }
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"); }
/// <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))); }
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(); }
/// <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))); }
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)) )); }
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); }
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); } }
/// <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)); }
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)); } }
public DapperCommand Build() { var expressions = BuildExpressions(this); var junctionFormat = BuildFormat(expressions); FormattableString command = FormattableStringFactory.Create( junctionFormat, expressions.ToArray()); return(new DapperCommand(command, values)); }