private IBookParty[] CollectPartiesForContracts() { var initaialParties = EMPTY_PARTY_LIST; var contractParties = __targets.Aggregate(initaialParties, (agr, factorPair) => GetContractParties(agr, factorPair.Value).ToArray()); return(contractParties); }
public string PrepareSubjectWithVariables() { if (!_variables.Any()) { return(_subject); } return(_variables.Aggregate(_subject, (current, subjectValue) => current.Replace("{%" + subjectValue.Key + "%}", Convert.ToString(subjectValue.Value)))); }
public void Add <TTask>() where TTask : IQueueableTask { var expression = _values.Aggregate <KeyValuePair <string, object>, ExplicitArgsExpression>(null, (current, keyValue) => current == null ? ObjectFactory.Container.With(keyValue.Key).EqualTo(keyValue.Value) : current.With(keyValue.Key).EqualTo(keyValue.Value)); _queueableTaskManager.Add(expression.GetInstance <TTask>()); }
/// <summary> /// Format a text string with dictionary values /// </summary> /// <param name="text"></param> /// <param name="tags"></param> /// <returns></returns> public static string FormatWithTags(this string text, object tags) { //return original string if no tag values given if (tags == null) { return(text); } string result; //initialize tag dictionary of values IDictionary <string, string> tagsDictionary = null; //if already dictionary just cast if (tags is IDictionary <string, string> ) { tagsDictionary = tags as IDictionary <string, string>; } else { //object or anonymous type so convert to dictionary of values tagsDictionary = TypeDescriptor .GetProperties(tags).Cast <PropertyDescriptor>() .ToDictionary(x => x.Name, x => x.GetValue(tags).ToString()); } //replace all tags with values from dictionary result = tagsDictionary.Aggregate(text, (current, tag) => current.Replace("{" + tag.Key + "}", (tag.Value ?? string.Empty).ToString())); return(result); }
public TypeDefinition(string name, IDictionary <string, string> props) { TypeName = name; Properties = props; hashCode = Properties.Aggregate( 17, (acc, pair) => (((acc * 31) + pair.Key.GetHashCode()) * 31) + pair.Value.GetHashCode()); }
public Environment(Language evaluator, IDictionary <string, object> builtins) { Language = evaluator; if (builtins != null) { builtins.Aggregate(this, (scope, pair) => { scope.Add(pair.Key, pair.Value); return(scope); }); } }
public int GetHashCode(IDictionary <TKey, TValue> obj) { unchecked { return(obj.Aggregate(0, (current, pair) => (current * 397) ^ pair.GetHashCode())); } }
/// <inheritdoc /> // ReSharper disable once MemberHidesStaticFromOuterClass public new IUnstartedProcessIO WithEnvironment(IDictionary <string, string> env) { return(env?.Aggregate( this as IUnstartedProcessIO, (acc, cur) => acc.WithEnvironmentVariable(cur.Key, cur.Value) ) ?? this); }
private static List <MemberDetails> GetMemberDetails <TSource>(IDictionary <string, string> propertyFullNames, ParameterExpression selectorParameter) => propertyFullNames.Aggregate(new List <MemberDetails>(), (list, next) => { Type t = typeof(TSource); List <string> fullNameList = next.Value.Split('.').Aggregate(new List <string>(), (lst, n) => { MemberInfo p = t.GetMemberInfo(n); t = p.GetMemberType(); lst.Add(p.Name); return(lst); }); list.Add(new MemberDetails { Selector = fullNameList.Aggregate ( (Expression)selectorParameter, (param, n) => Expression.MakeMemberAccess ( param, param.Type.GetMemberInfo(n) ) ), MemberName = next.Key, Type = t }); return(list); });
/// <summary> /// Parses the specified notification text. /// </summary> /// <param name="textLayout">The text layout.</param> /// <returns></returns> internal string Parse(string textLayout = null) { if (String.IsNullOrWhiteSpace(textLayout)) { return(NotificationText); } if (!textLayout.Contains("{") || NotificationID == 0) { return(textLayout); } var pairs = Util.ParseYaml(NotificationText) as YamlMappingNode; IDictionary <string, string> parsedDict = GetParsedDictionary(textLayout, pairs); foreach (KeyValuePair <YamlNode, YamlNode> pair in pairs) { m_parser.Parse(m_notification, pair, parsedDict); } string parsedText = parsedDict.Aggregate(textLayout, (current, pair) => current.Replace("{" + pair.Key + "}", pair.Value.Trim('\''))); return(parsedText.Contains("{") ? NotificationText : parsedText); }
//public AbstractSearch BuildProperties(IDictionary<string, string> search) //{ // var key = string.Empty; // var val = string.Empty; // var comparator = TextComparators.Equals; // foreach (var s in search) // { // if (s.Key.Contains("_")) // { // comparator = (TextComparators)Enum.Parse(typeof(TextComparators), s.Value); // } else // { // key = s.Key; // val = s.Value; // } // } // return BuildPropertyText<Customer>(key, val, s.Value); ; //} private ExpandoObject ConvertDictToExpando <T>(IDictionary <string, string> input) { dynamic eo = input.Aggregate(new ExpandoObject() as IDictionary <string, object>, (a, p) => { a.Add(p.Key, p.Value); return(a); }); return(eo); }
/// <summary> /// 字典型数据转换为URL参数字符串 /// </summary> /// <param name="this">字典数据源</param> /// <param name="seed">起点初始字符串,默认为空字符串</param> /// <param name="isAsciiSort">是否ASCII排序,默认升序排序</param> /// <param name="isRemoveNull">是否移除空值,默认移除</param> /// <returns>string</returns> public static string ToUrl <T, S>(this IDictionary <T, S> @this, string seed = "", bool isAsciiSort = true, bool isRemoveNull = true) { var result = string.Empty; try { //移除所有空值参数 if (isRemoveNull) { @this = @this.Where(o => o.Value?.ToString().IsNullOrEmpty() == false).ToDictionary(o => o.Key, o => o.Value); } //对参数键值对进行ASCII升序排序 if (isAsciiSort) { //C#默认的不是ASCII排序,正确的ASCII排序规则:数字、大写字母、小写字母的顺序 @this = @this.OrderBy(o => o.Key, new OrdinalComparer()).ToDictionary(o => o.Key, o => o.Value); } //拼接url result = @this.Aggregate(seed, _ => $"{_.Key}={_.Value?.ToString()}&", "&"); } catch (Exception ex) { LogHelper.Error(ex, "字典型数据转换为URL参数字符串"); } return(result); }
public string GetMessageBody(string module, string key, IDictionary <string, string> values) { if (string.IsNullOrEmpty(_module)) { throw new ArgumentNullException(_module); } string template = null; switch (_type) { case MessagingType.Email: template = _module.GetHtmlTemplate <EmailTemplate>(_bodyTemplatePath, key); break; } if (template == null) { return(null); } if (!values.ContainsKey("ApplicationName")) { values["ApplicationName"] = _appInfo.ApplicationName; } return(values.Aggregate(template, (current, v) => current.Replace("{{" + v.Key + "}}", v.Value))); }
public static async Task <List <LyricFormat> > GetLyricsAsync(IDictionary <string, string> data) { try { string act = "GetResembleLyric2"; Debug.WriteLine(Resources.ResourceManager.GetString(act)); var content = data.Aggregate(Resources.ResourceManager.GetString(act), (o, i) => o.Replace(i.Key, i.Value)); Debug.WriteLine(content); var wr = (HttpWebRequest)WebRequest.Create(@"http://lyrics.alsong.co.kr/alsongwebservice/service1.asmx"); wr.ServicePoint.Expect100Continue = false; wr.Method = "POST"; wr.UserAgent = "gSOAP"; wr.ContentType = "application/soap+xml; charset=UTF-8"; wr.Headers.Add("SOAPAction", "ALSongWebServer/" + act); using (var rq = new StreamWriter(wr.GetRequestStream())) { rq.Write(content); } using (var rp = new StreamReader((await wr.GetResponseAsync()).GetResponseStream())) { return(WebUtility.HtmlDecode(rp.ReadToEnd().Split(new[] { "<strLyric>", "</strLyric>" }, StringSplitOptions.None)[1]) .Split(new[] { "<br>" }, StringSplitOptions.RemoveEmptyEntries) .Select(i => new LyricFormat(i)) .Where(i => i.Text.Length != 0) .ToList()); } } catch { return(null); } }
private decimal ComputeResultValue(PayTagGateway tagConfig, IDictionary <TagRefer, PayrollResult> results) { decimal resultValue = results.Aggregate(decimal.Zero, (agr, termItem) => (decimal.Add(agr, InnerComputeResultValue(tagConfig, this.TagCode, termItem)))); return(resultValue); }
public static string ToUrlAlias(this string value, IDictionary <string, string> charReplacements, bool replaceDoubleDashes, bool stripNonAscii, bool urlEncode) { value = value.ToLowerInvariant(); charReplacements = charReplacements ?? (IDictionary <string, string>) new Dictionary <string, string>(); value = charReplacements.Aggregate <KeyValuePair <string, string>, string>(value, (Func <string, KeyValuePair <string, string>, string>)((current, kvp) => current.Replace(kvp.Key, kvp.Value))); if (stripNonAscii) { value = Encoding.ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(Encoding.ASCII.EncodingName, (EncoderFallback) new EncoderReplacementFallback(string.Empty), (DecoderFallback) new DecoderExceptionFallback()), Encoding.UTF8.GetBytes(value))); IEnumerable <int> validCodeRanges = Enumerable.Range(48, 10).Concat <int>(Enumerable.Range(97, 26)); StringBuilder stringBuilder = new StringBuilder(); foreach (char ch in value.Where <char>((Func <char, bool>)(c => { if (!charReplacements.Values.Contains(c.ToString())) { return(validCodeRanges.Contains <int>((int)c)); } return(true); }))) { stringBuilder.Append(ch); } value = stringBuilder.ToString(); } value = value.Trim('-', '_'); value = replaceDoubleDashes ? Regex.Replace(value, "([-_]){2,}", "$1", RegexOptions.Compiled) : value; if (!urlEncode) { return(value); } return(WebUtility.UrlEncode(value)); }
private static StringContent GetStringContentFromParameters(IDictionary <string, string> parametersDictionary) { var limit = 32000; var content = new StringContent(parametersDictionary.Aggregate(new StringBuilder(), (sb, nxt) => { var sbInternal = new StringBuilder(); if (sb.Length > 0) { sb.Append("&"); } var loops = nxt.Value.Length / limit; for (var i = 0; i <= loops; i++) { if (i < loops) { sbInternal.Append(Uri.EscapeDataString(nxt.Value.Substring(limit * i, limit))); } else { sbInternal.Append(Uri.EscapeDataString(nxt.Value.Substring(limit * i))); } } return(sb.Append(nxt.Key + "=" + sbInternal.ToString())); }).ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); return(content); }
/// <summary> /// Expand transaction for API Methods: Pay/Block /// </summary> /// <param name="info">Object that contains params for transaction's processing</param> /// <param name="customFields">Addition fields for processing operation</param> /// <param name="customerKey">Customer's identifier in Payture AntiFraud system</param> /// <param name="paytureId">Payment's identifier in Payture AntiFraud system</param> /// <returns>current expanded transaction</returns> public Transaction ExpandTransaction(PayInfo info, IDictionary <string, string> customFields, string customerKey, string paytureId) { if (info == null) { return(this); } _requestKeyValuePair.Add(PaytureParams.PayInfo, info.GetPropertiesString()); _requestKeyValuePair.Add(PaytureParams.OrderId, info.OrderId); _requestKeyValuePair.Add(PaytureParams.Amount, info.Amount); if (customFields != null && customFields.Count() != 0) { _requestKeyValuePair.Add(PaytureParams.CustomFields, customFields.Aggregate("", (a, c) => a += $"{c.Key}={c.Value};")); } if (!String.IsNullOrEmpty(customerKey)) { _requestKeyValuePair.Add(PaytureParams.CustomerKey, customerKey); } if (!String.IsNullOrEmpty(paytureId)) { _requestKeyValuePair.Add(PaytureParams.PaytureId, paytureId); } ExpandTransaction(); _expanded = true; return(this); }
public void PostRequest(string url, IDictionary <string, string> parameters) { var paramz = parameters.Aggregate(new NameValueCollection(), (seed, current) => { seed.Add(current.Key, current.Value); return(seed); }); using (var client = new WebClient()) { try { var responsebytes = client.UploadValues(url, paramz); var responsebody = Encoding.UTF8.GetString(responsebytes); } catch (WebException ex) { var response = (ex.Response as HttpWebResponse); if (response.StatusCode == HttpStatusCode.BadRequest) { throw new Exception("WebApi error : " + GetResponseData(ex.Response)); } } } }
public IHsmModelHolder Apply(IDictionary <IHsmModelHolder, double> probabilitiesByModels) { double totalSum = probabilitiesByModels.Sum(x => x.Value); IDictionary <IHsmModelHolder, double> weightedProbabilitiesByModels = probabilitiesByModels.ToDictionary(entry => entry.Key, entry => Math.Log10(entry.Value / totalSum)); return(weightedProbabilitiesByModels.Aggregate((l, r) => l.Value > r.Value ? l : r).Key); }
protected string EvaluateExpression(string expression, IDictionary <string, string> variablesDictionary) { var variables = ""; if (variablesDictionary != null) { variables = variablesDictionary.Aggregate("", (s, x) => string.Format("{0} @{1}: {2};", s, x.Key, x.Value)); } var less = string.Format("{1} .def {{\nexpression:\n{0}\n;}}", expression, variables); var css = Evaluate(less); if (string.IsNullOrEmpty(css)) { return(""); } var start = css.IndexOf("expression:"); var end = css.LastIndexOf(DefaultEnv().Compress ? '}' : ';'); return(css.Substring(start + 11, end - start - 11).Trim()); }
public void LogTelemetry(string eventName, IDictionary <string, string> properties) { if (_output != null) { _output?.WriteLine($"telemetry {eventName}: {properties.Aggregate(string.Empty, (sum, piece) => $"{sum}, {piece.Key} = {piece.Value}")}"); } }
/// <summary> /// 读取转换参数至字典 /// </summary> private async Task <NameValueCollection> ParseParametersFromBody(HttpRequestMessage request, JsonSerializerSettings jsonSerializerSettings) { string cacheKey = typeof(WrapPostParameterBinding).FullName; if (!request.Properties.TryGetValue(cacheKey, out object result)) { MediaTypeHeaderValue contentType = request.Content.Headers.ContentType; if (contentType.MediaType.StartsWith("application/json")) { string content = await request.Content.ReadAsStringAsync(); IDictionary <string, object> values = JsonConvert.DeserializeObject <Dictionary <string, object> >(content, jsonSerializerSettings); result = values.Aggregate(new NameValueCollection(), (seed, current) => { seed.Add(current.Key, current.Value?.ToString()); return(seed); }); } else if (contentType.MediaType.StartsWith("application/x-www-form-urlencoded")) { result = await request.Content.ReadAsFormDataAsync(); } else { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } request.Properties.Add(cacheKey, result); } return((NameValueCollection)result); }
private static MultipartFormDataContent GetMultipartContent(IDictionary <string, object> parameters) { return(parameters.Aggregate( new MultipartFormDataContent(), (multipartContent, kvp) => { var key = kvp.Key; var value = kvp.Value; HttpContent content; if (value is Stream) { content = new StreamContent((Stream)value); } else { content = new StringContent(value.ToString(), Encoding.UTF8); } multipartContent.Add(content, key); return multipartContent; })); }
private static DeepCompareResult DeepCompare(this object left, IDictionary <string, KeyValuePair <string, object> > rightLeaves) { // optimization removed: it doenst fill the 'EqualValues' list // if (ReferenceEquals(left, right)) // return new DeepCompareResult(); var leftLeafEnumerator = left.Flatten().GetEnumerator(); var compareResult = new DeepCompareResult(); foreach (var leftLeaf in left.Flatten()) { if (rightLeaves.TryGetValue(leftLeaf.Key, out var rightLeaf)) { DeepCompareLeaves(leftLeaf, rightLeaf, compareResult); rightLeaves.Remove(leftLeaf.Key); } else { compareResult.Missing.Right.Add(leftLeaf.Key); } } // add all uncompared left proerties to the result object return(rightLeaves.Aggregate(compareResult, (cr, kv) => { cr.Missing.Left.Add(kv.Key); return cr; })); }
public override string ToString() { return(string.Format("{0}\r\n{1}\r\n", Status, Headers != null ? Headers.Aggregate("", (acc, kv) => acc += string.Format("{0}: {1}\r\n", kv.Key, kv.Value)) : "")); }
public static Document CreateDocumentWithProperties(Database db, IDictionary <String, Object> properties) { var doc = db.CreateDocument(); Assert.IsNotNull(doc); Assert.IsNull(doc.CurrentRevisionId); Assert.IsNull(doc.CurrentRevision); Assert.IsNotNull("Document has no ID", doc.Id); // 'untitled' docs are no longer untitled (8/10/12) try { doc.PutProperties(properties); } catch (Exception e) { Log.E(Tag, "Error creating document", e); Assert.IsTrue(false, "can't create new document in db:" + db.Name + " with properties:" + properties.Aggregate(new StringBuilder(" >>> "), (str, kvp) => { str.AppendFormat("'{0}:{1}' ", kvp.Key, kvp.Value); return(str); }, str => str.ToString())); } Assert.IsNotNull(doc.Id); Assert.IsNotNull(doc.CurrentRevisionId); Assert.IsNotNull(doc.UserProperties); Assert.AreEqual(db.GetDocument(doc.Id), doc); return(doc); }
public MultipartDataBuilder KeyValuePairs(IDictionary<string, string> pairs) { return pairs.Aggregate( this, (current, pair) => current.KeyValuePair(pair.Key, pair.Value) ); }
private Uri GetServiceUri(string endPoint, IDictionary <string, object> variables, IDictionary <string, string> requestParameters) { endPoint = variables.Aggregate(endPoint, (current, entry) => current.Replace($"{{{entry.Key}}}", entry.Value.ToString())); var query = new StringBuilder(); foreach (var entry in requestParameters) { query.Append(query.Length == 0 ? "?" : "&") .Append(WebUtility.UrlEncode(entry.Key)) .Append("=") .Append(WebUtility.UrlEncode(entry.Value)); } if (query.Length > 0) { endPoint += query.ToString(); } if (endPoint.StartsWith("/")) { endPoint = endPoint.Substring(1); } return(new Uri(baseUri, endPoint)); }
/// <summary> /// Converts the dictionary to attributes. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <returns></returns> public static string ConvertDictionaryToAttributes(IDictionary<string, object> dictionary) { if (dictionary != null && dictionary.Any()) { return dictionary.Aggregate(" ", (c, att) => c + String.Format("{0}=\"{1}\"", att.Key, att.Value)); } return String.Empty; }
public string GetTemplatedBody(string template, IDictionary<string, string> model = null) { if (model != null) { template = model.Aggregate(template, (current, item) => current.Replace(string.Format("[{0}]", item.Key), item.Value)); } return template; }
/// <summary> /// Gets a message that describes the current exception. /// </summary> /// <value></value> /// <returns>The error message that explains the reason for the exception, or an empty string("").</returns> private static string Format(Error error, IDictionary<string, object> dictionary) { string message = error.Code; if (dictionary.Any()) { message += " { " + dictionary.Aggregate(message, (current, keyValuePair) => current + (keyValuePair.Key + "=" + keyValuePair.Value)) + " } "; } return message; }
public static string GenerateBatchBody(IDictionary<string, IEnumerable<Event>> eventDataByCollection) { return eventDataByCollection.Aggregate(new JObject(), (json, edbc) => { var collectionName = edbc.Key; json[collectionName] = edbc.Value.Aggregate(new JArray(), (events, ed) => { events.Add(ed.Data); return events; }); return json; }).ToString(); }
private string GetStringFor(IDictionary<string, object> map, byte level) { if (level > 7) { throw new NotSupportedException($"Unsupported nesting level ({level}) for {nameof(MultiLevelMapFormatter)}."); } char pair_separator = (char)(level - 1); char keyvalue_separator = (char)(level); return map.Aggregate(new StringBuilder(), (whole, next) => { object value = next.Value; if (value is IDictionary<string, object>) { value = GetStringFor(value as IDictionary<string, object>, (byte)(level + 2)); } return whole.AppendFormat("{0}{1}{2}{3}", next.Key, keyvalue_separator, value, pair_separator); }).ToString(); }
protected static string EvaluateExpression(string expression, IDictionary<string, string> variablesDictionary) { var variables = ""; if (variablesDictionary != null) variables = variablesDictionary.Aggregate("", (s, x) => string.Format("{0}\n @{1}: {2};", s, x.Key, x.Value)); var less = string.Format(".def {{{0}\n expression: {1};\n}}", variables, expression); var css = Evaluate(less); if (string.IsNullOrEmpty(css)) return ""; var start = css.IndexOf(" expression: "); var end = css.LastIndexOf("}"); return css.Substring(start + 14, end - start - 16); }
internal static Uri BuildUri(string baseUrl, string resource, IDictionary<string, string> urlSegments, IDictionary<string, string> queryStrings) { // Replace the URL Segments if (urlSegments != null) { foreach (var urlSegment in urlSegments) { resource = resource.Replace(string.Format("{{{0}}}", urlSegment.Key), Uri.EscapeUriString(urlSegment.Value ?? String.Empty)); } // Remove trailing slash resource = resource.TrimEnd('/'); } // Add the query strings if (queryStrings != null) { var queryString = queryStrings .Aggregate(new StringBuilder(), (sb, kvp) => { if (sb.Length > 0) sb = sb.Append("&"); if (kvp.Value != null) return sb.Append(string.Format("{0}={1}", Uri.EscapeUriString(kvp.Key), Uri.EscapeDataString(kvp.Value))); return sb; }) .ToString(); // If we have a querystring, append it to the resource if (!string.IsNullOrEmpty(queryString)) { if (resource.Contains("?")) resource = string.Format("{0}&{1}", resource, queryString); else resource = string.Format("{0}?{1}", resource, queryString); } } resource = CombineUriParts(baseUrl, resource); return new Uri(resource, UriKind.RelativeOrAbsolute); }
/// <summary> /// Invokes the command with the specified parameters. /// </summary> /// <param name="parameters">The parameters.</param> public void Invoke(IDictionary<string, string> parameters) { _parameters = parameters.Aggregate( new Dictionary<string, string>(), (map, pair) => { map.Add(pair.Key.ToLower(), pair.Value); return map; }); var updates = new Updater(BaseDirectory, DatabaseServer, DatabaseName).GetUpdates(); if (updates == null || updates.Count == 0) { return; } foreach (var update in updates) { UpdateDatabase(update); } }
/// <summary> /// Perform an HTTP POST on the supplied resource /// </summary> /// <param name="uri">The resource to perform a POST on</param> /// <param name="data">The form data to post to the service</param> /// <returns>The response from the web service</returns> public string Post(string uri, IDictionary<string, string> data) { var parameters = data.Aggregate(new StringBuilder(), (builder, pair) => builder.AppendFormat("{0}={1}&", pair.Key, WebUtility.HtmlEncode(pair.Value))); var values = parameters.ToString(0, parameters.Length - 1); var request = WebRequest.Create(uri); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = values.Length; using (var stream = request.GetRequestStream()) using (var writer = new StreamWriter(stream)) { writer.Write(values); } using (var stream = request.GetResponse().GetResponseStream()) using (var reader = new StreamReader(stream)) { var content = reader.ReadToEnd(); return content; } }
/// <summary> /// Converts string to a URL alias. /// </summary> /// <param name="value">The value.</param> /// <param name="charReplacements">The char replacements.</param> /// <param name="replaceDoubleDashes">if set to <c>true</c> replace double dashes.</param> /// <param name="stripNonAscii">if set to <c>true</c> strip non ASCII.</param> /// <param name="urlEncode">if set to <c>true</c> URL encode.</param> /// <returns></returns> /// <remarks> /// This ensures that ONLY ascii chars are allowed and of those ascii chars, only digits and lowercase chars, all /// punctuation, etc... are stripped out, however this method allows you to pass in string's to replace with the /// specified replacement character before the string is converted to ascii and it has invalid characters stripped out. /// This allows you to replace strings like & , etc.. with your replacement character before the automatic /// reduction. /// </remarks> public string LegacyToUrlAlias(string value, IDictionary<string, string> charReplacements, bool replaceDoubleDashes, bool stripNonAscii, bool urlEncode) { // to lower case invariant // replace chars one by one using charReplacements // (opt) convert to ASCII then remove anything that's not ASCII // trim - and _ then (opt) remove double - // (opt) url-encode // charReplacement is actually *string* replacement ie it can replace " " by a non-breaking space // so it's kind of a pre-filter actually... // we need pre-filters, and post-filters, within each token... // not so... we may want to replace with a space BEFORE cutting into tokens... //first to lower case value = value.ToLowerInvariant(); //then replacement chars value = charReplacements.Aggregate(value, (current, kvp) => current.Replace(kvp.Key, kvp.Value)); //then convert to only ascii, this will remove the rest of any invalid chars if (stripNonAscii) { value = Encoding.ASCII.GetString( Encoding.Convert( Encoding.UTF8, Encoding.GetEncoding( Encoding.ASCII.EncodingName, new EncoderReplacementFallback(String.Empty), new DecoderExceptionFallback()), Encoding.UTF8.GetBytes(value))); //remove all characters that do not fall into the following categories (apart from the replacement val) var validCodeRanges = //digits Enumerable.Range(48, 10).Concat( //lowercase chars Enumerable.Range(97, 26)); var sb = new StringBuilder(); foreach (var c in value.Where(c => charReplacements.Values.Contains(c.ToString(CultureInfo.InvariantCulture)) || validCodeRanges.Contains(c))) { sb.Append(c); } value = sb.ToString(); } //trim dashes from end value = value.Trim('-', '_'); //replace double occurances of - or _ value = replaceDoubleDashes ? Regex.Replace(value, @"([-_]){2,}", "$1", RegexOptions.Compiled) : value; //url encode result return urlEncode ? System.Web.HttpUtility.UrlEncode(value) : value; }
public static string ToNewRelicSafeString(this string str, IDictionary<string, string> reservedWords) { return reservedWords.Aggregate(str, (current, reservedWord) => current.ReplaceCaseInsensitiveFind(reservedWord.Key, reservedWord.Value)); }
private static string CallServer(IDictionary<string, string> data) { if (string.IsNullOrEmpty(_apikey)) { throw new SubunoApiError("API key not set."); } HttpWebRequest request; HttpWebResponse response = null; StreamReader reader; StringBuilder sbSource; //add apikey to the data packet. data.Add("apikey", _apikey); // serialize data. string urlencoding = string.Empty; urlencoding = data.Aggregate(urlencoding, (current, pair) => current + "&" + HttpUtility.UrlEncode(pair.Key, Encoding.GetEncoding("UTF-8")) + "=" + HttpUtility.UrlEncode(pair.Value, Encoding.GetEncoding("UTF-8"))); urlencoding = urlencoding.Substring(1); // remove first & UriBuilder builder = null; try { builder = new UriBuilder(new Uri(_server_uri + "?" + urlencoding)); } catch (UriFormatException e) { Console.WriteLine(e.ToString()); } try { // Create and initialize the web request request = WebRequest.Create(builder.ToString()) as HttpWebRequest; // Get response response = request.GetResponse() as HttpWebResponse; if (request.HaveResponse && response != null) { // Get the response stream reader = new StreamReader(response.GetResponseStream()); // Read it into a StringBuilder sbSource = new StringBuilder(reader.ReadToEnd()); // Console application output return sbSource.ToString(); } } catch (WebException wex) { // This exception will be raised if the server didn't return 200 - OK // Try to retrieve more information about the network error if (wex.Response != null) { using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response) { Console.WriteLine( "The server returned '{0}' with the status code {1} ({2:d}).", errorResponse.StatusDescription, errorResponse.StatusCode, errorResponse.StatusCode); } } } finally { if (response != null) { response.Close(); } } return string.Empty; }
public static string DoReplace(this string source, IDictionary<string, string> dic) { return dic.Aggregate(source, (current, pair) => current.Replace("${" + pair.Key + "}", pair.Value)); }
public byte[] Serialize(IDictionary<string, object> map) { return Encoding.UTF8.GetBytes(map.Aggregate(new StringBuilder(), (whole, next) => whole.AppendFormat("{0}\x1{1}\x0", next.Key, next.Value)).ToString()); }
private string ExpandChutzpahVariables(IDictionary<string, string> chutzpahCompileVariables, string str) { if (str == null) { return null; } return chutzpahCompileVariables.Aggregate(str, (current, pair) => current.Replace(pair.Key, pair.Value)); }
protected string EvaluateExpression(string expression, IDictionary<string, string> variablesDictionary, out List<string> logMessages) { var variables = ""; if (variablesDictionary != null) variables = variablesDictionary.Aggregate("", (s, x) => string.Format("{0} @{1}: {2};", s, x.Key, x.Value)); var less = string.Format("{1} .def {{\nexpression:\n{0}\n;}}", expression, variables); TestLogger testLogger; var css = Evaluate(less, out testLogger); logMessages = testLogger.LogMessages; if (string.IsNullOrEmpty(css)) return ""; return ExtractExpressionResult(css); }
public string Execute(IDictionary<string,string> parameters) { return parameters.Aggregate(source, (t,p) => t.Replace("{"+p.Key+"}",p.Value)); }
/// <summary> /// <para>Returns a new string in which all occurrences of the specified tokens in the current instance are replaced with the provided replacement values.</para> /// <para>A token is designated in a string by surrounding it with curly braces (example: {MyToken}).</para> /// <para>A token must consist of one or more valid "word characters" (think valid variable name) and is case-sensitive.</para> /// <para>Curly braces can be escaped by using double braces. The double braces will be /// replaced with single braces (example: "{{something}}" becomes "{something}").</para> /// <para>Any token without a replacement value specified will be untouched and appear in the returned string exactly as in the source.</para> /// </summary> /// <param name="source">The source string.</param> /// <param name="replacements">The replacement values.</param> /// <returns>A new string in which all occurrences of the specified tokens in the current instance are replaced with the provided replacement values.</returns> public static string Format(this string source, IDictionary<string, string> replacements) { if (source.IsNullOrWhiteSpace() || replacements == null) { return source; } string replaced = replacements.Aggregate(source, (current, pair) => FormatRegex.Replace(current, new MatchEvaluator(match => (match.Groups[FormatTokenGroupName].Value == pair.Key ? pair.Value : match.Value)))); return replaced.Replace("{{", "{").Replace("}}", "}"); }
public string Present(string displayFormat, IDictionary<string, object> arguments) { return arguments.Aggregate(displayFormat, (current, pair) => current.Replace("{" + pair.Key + "}", pair.Value.ToString())); }
/// <summary> /// Returns a new string in which all occurences of specified strings are replaced by other specified strings. /// </summary> /// <param name="text">The string to filter.</param> /// <param name="replacements">The replacements definition.</param> /// <returns>The filtered string.</returns> public string ReplaceMany(string text, IDictionary<string, string> replacements) { // Have done various tests, implementing my own "super fast" state machine to handle // replacement of many items, or via regexes, but on short strings and not too // many replacements (which prob. is going to be our case) nothing can beat this... // (at least with safe and checked code -- we don't want unsafe/unchecked here) // Note that it will do chained-replacements ie replaced items can be replaced // in turn by another replacement (ie the order of replacements is important) return replacements.Aggregate(text, (current, kvp) => current.Replace(kvp.Key, kvp.Value)); }
protected string EvaluateExpression(string expression, IDictionary<string, string> variablesDictionary) { var variables = ""; if (variablesDictionary != null) variables = variablesDictionary.Aggregate("", (s, x) => string.Format("{0} @{1}: {2};", s, x.Key, x.Value)); var less = string.Format("{1} .def {{\nexpression:\n{0}\n;}}", expression, variables); var css = Evaluate(less); if (string.IsNullOrEmpty(css)) return ""; var start = css.IndexOf("expression:"); var end = css.LastIndexOf(DefaultEnv().Compress ? '}' : ';'); return css.Substring(start + 11, end - start - 11).Trim(); }
public static Document CreateDocumentWithProperties(Database db, IDictionary<String, Object> properties) { var doc = db.CreateDocument(); Assert.IsNotNull(doc); Assert.IsNull(doc.CurrentRevisionId); Assert.IsNull(doc.CurrentRevision); Assert.IsNotNull("Document has no ID", doc.Id); // 'untitled' docs are no longer untitled (8/10/12) try { doc.PutProperties(properties); } catch (Exception e) { Log.E(Tag, "Error creating document", e); Assert.IsTrue( false, "can't create new document in db:" + db.Name + " with properties:" + properties.Aggregate(new StringBuilder(" >>> "), (str, kvp)=> { str.AppendFormat("'{0}:{1}' ", kvp.Key, kvp.Value); return str; }, str=>str.ToString())); } Assert.IsNotNull(doc.Id); Assert.IsNotNull(doc.CurrentRevisionId); Assert.IsNotNull(doc.UserProperties); Assert.AreEqual(db.GetDocument(doc.Id), doc); return doc; }
private static void OutputLanguageScores(IDictionary<string, double> scores, string bestLanguage) { string languagesAndScores = ""; KeyValuePair<string, double> maxLanguage = scores.Aggregate((l, r) => l.Value > r.Value ? l : r); KeyValuePair<string, double> minLanguage = scores.Aggregate((l, r) => l.Value < r.Value ? l : r); scores.Remove(maxLanguage.Key); KeyValuePair<string, double> secondLanguage = scores.Aggregate((l, r) => l.Value > r.Value ? l : r); scores.Add(maxLanguage.Key, maxLanguage.Value); double scorePercentageDiff = Math.Round((maxLanguage.Value - secondLanguage.Value) / (maxLanguage.Value - minLanguage.Value) * 100, 2); foreach (KeyValuePair<string, double> keyValuePair in scores) { languagesAndScores += keyValuePair.Key + "\t" + keyValuePair.Value + (keyValuePair.Key == bestLanguage ? "***" : "") + "\n"; } Console.WriteLine(languagesAndScores + "\nDifference between first and runner-up: " + scorePercentageDiff + "%."); }
internal static void ReplaceVariables(ref string input, IDictionary<string, string> variables) { input = variables.Aggregate(input, (current, variable) => current.Replace(variable.Key, variable.Value)); }