/// <summary> /// Load a collection of objects from a string /// </summary> /// <param name="content"> /// The string to load the objects from. /// </param> /// <param name="typeMap"> /// A map from apiVersion/kind to Type. For example "v1/Pod" -> typeof(V1Pod). If null, a default mapping will /// be used. /// </param> /// <returns>collection of objects</returns> public static List <object> LoadAllFromString(string content, IDictionary <string, Type> typeMap = null) { var mergedTypeMap = new Dictionary <string, Type>(ModelTypeMap); // merge in KVPs from typeMap, overriding any in ModelTypeMap typeMap?.ToList().ForEach(x => mergedTypeMap[x.Key] = x.Value); var types = new List <Type>(); var parser = new Parser(new StringReader(content)); parser.Consume <StreamStart>(); while (parser.Accept <DocumentStart>(out _)) { var obj = Deserializer.Deserialize <KubernetesObject>(parser); types.Add(mergedTypeMap[obj.ApiVersion + "/" + obj.Kind]); } parser = new Parser(new StringReader(content)); parser.Consume <StreamStart>(); var ix = 0; var results = new List <object>(); while (parser.Accept <DocumentStart>(out _)) { var objType = types[ix++]; var obj = Deserializer.Deserialize(parser, objType); results.Add(obj); } return(results); }
public static string Dump(string sql, IDictionary<string, object> parameters, ISqlDialect dialect = null) { if (parameters == null) return sql; var param = parameters.ToList(); for (var i = 0; i < param.Count; i++) { var name = param[i].Key; if (!name.StartsWith("@")) param[i] = new KeyValuePair<string,object>("@" + name, param[i].Value); } param.Sort((x, y) => y.Key.Length.CompareTo(x.Key.Length)); var sb = new StringBuilder(sql); foreach (var pair in param) sb.Replace(pair.Key, DumpParameterValue(pair.Value, dialect)); var text = DatabaseCaretReferences.Replace(sb.ToString()); dialect = dialect ?? SqlSettings.DefaultDialect; var openBracket = dialect.OpenQuote; if (openBracket != '[') text = BracketLocator.ReplaceBrackets(text, dialect); var paramPrefix = dialect.ParameterPrefix; if (paramPrefix != '@') text = ParamPrefixReplacer.Replace(text, paramPrefix); return text; }
public void Can_serialize_content_as_complex_associative_array() { var message = new MandrillMessage(); var data = new IDictionary<string, object>[] { new Dictionary<string, object> { {"sku", "apples"}, {"unit_price", 0.20}, }, new Dictionary<string, object> { {"sku", "oranges"}, {"unit_price", 0.40}, } }; message.GlobalMergeVars.Add(new MandrillMergeVar() { Name = "test", Content = data.ToList() }); var json = JObject.FromObject(message, MandrillSerializer.Instance); json["global_merge_vars"].Should().NotBeEmpty(); var result = json["global_merge_vars"].First["content"] .ToObject<List<Dictionary<string, object>>>(MandrillSerializer.Instance); result[0]["sku"].Should().Be("apples"); result[0]["unit_price"].Should().Be(0.20); result[1]["sku"].Should().Be("oranges"); result[1]["unit_price"].Should().Be(0.40); }
public async static Task <string> PostMultipartFormDataAsync(string url, IDictionary <string, string> dicForm, IDictionary <string, FileSimpleInfo> dicFiles, IDictionary <string, string> headers = null) { using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)) using (MultipartFormDataContent content = new MultipartFormDataContent()) { //添加表单内容 dicForm.ToList().ForEach(item => { content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(item.Value)), item.Key); }); //添加多文件内容 dicFiles.ToList().ForEach(item => { content.Add(new ByteArrayContent(item.Value.Content), item.Key, item.Value.FileName); }); request.Content = content; //添加http请求头 headers?.ToList().ForEach(item => { request.Headers.Add(item.Key, item.Value); }); using (HttpResponseMessage response = await httpClient.SendAsync(request)) { response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStringAsync()); } } }
public void Open(string url, string protocol, IDictionary <string, string> headers) { Close(); if (url.StartsWith("https")) { url = url.Replace("https://", "wss://"); } else if (url.StartsWith("http")) { url = url.Replace("http://", "ws://"); } #if net20 || net35 var customHeaderItems = new List <KeyValuePair <string, string> >(); if (headers != null) { customHeaderItems.AddRange(headers.ToArray()); } websocket = new WebSocket(url, protocol, null, customHeaderItems, "Websockets.Standard", WebSocketVersion.Rfc6455); #else websocket = new WebSocket(url, protocol, null, headers?.ToList()); #endif websocket.Opened += Websocket_Opened; websocket.Error += Websocket_Error; websocket.Closed += Websocket_Closed; websocket.MessageReceived += Websocket_MessageReceived; websocket.Open(); }
public AmqpConnectionParameters(IDictionary<string, string> parameters) { this.SetDefaultValues(); parameters .ToList<KeyValuePair<string, string>>() .ForEach(param => this.Set(param.Key, param.Value)); }
public ReportRunner( ReportFormat reportFormat, string reportPath, IDictionary<string, object> reportParameters) : this(reportFormat, reportPath, reportParameters != null ? reportParameters.ToList() : null) { }
public void DispatchDoesNotMutateInputRouteValues( DefaultRouteDispatcher sut, MethodCallExpression method, IDictionary<string, object> routeValues) { var expected = routeValues.ToList(); sut.Dispatch(method, routeValues); Assert.True(expected.SequenceEqual(routeValues)); }
public void SetOutputArguments(IDictionary<string, string> output) { RemoveArgument(output, StartArgument.Replace("/", "")); RemoveArgument(output, EndArgument.Replace("/", "")); foreach (var kvp in output.ToList()) { output[kvp.Key] = string.Format("{0}.{1}.{2}.pout", kvp.Value, Start, End); } }
/// <summary> /// Creates Tag objects from a provided dictionary of string tags along with integer values indicating the weight of each tag. /// This overload is suitable when you have a list of already weighted tags, i.e. from a database query result. /// </summary> /// <param name="weightedTags">A dictionary that takes a string for the tag text (as the dictionary key) and an integer for the tag weight (as the dictionary value).</param> /// <param name="rules">A TagCloudGenerationRules object to decide how the cloud is generated.</param> /// <returns>A list of Tag objects that can be used to create the tag cloud.</returns> public static IEnumerable<Tag> CreateTags(IDictionary<string, int> weightedTags, TagCloudGenerationRules generationRules) { #region Parameter validation if (weightedTags == null) throw new ArgumentNullException("weightedTags"); if (generationRules == null) throw new ArgumentNullException("generationRules"); #endregion return CreateTags(weightedTags.ToList(), generationRules); }
/// <summary> /// Converts the given collection of extension properties and their identifiers to full paths. /// </summary> internal static Dictionary<string, string> GetInstalledExtensionPaths(IVsExtensionManager extensionManager, IDictionary<string, string> extensionIds) { // Update installed Extensions var installedExtensionPaths = new Dictionary<string, string>(); extensionIds.ToList().ForEach(ie => { installedExtensionPaths.Add(ie.Key, GetInstalledExtensionPath(extensionManager, ie.Value)); }); return installedExtensionPaths; }
public IDbCommand BuildCommand(IDbConnection connection, string sql, IDictionary<string, object> parameters) { var cmd = connection.CreateCommand(); cmd.Connection = connection; cmd.CommandText = sql; parameters.ToList() .ForEach(cmd.AddParameter); return cmd; }
/// <summary> /// Append stats distributed in castle /// </summary> /// <param name="castleStatsDictionary">Stats distributed in castle</param> /// <param name="calculationResult">Current calculation result</param> public void Calculate(IDictionary<StatTypeEnum, byte> castleStatsDictionary, CalculationResult calculationResult) { if (castleStatsDictionary == null) throw new ArgumentNullException("castleStatsDictionary"); if (calculationResult == null) throw new ArgumentNullException("calculationResult"); castleStatsDictionary .ToList() .ForEach(y => applyStatValue(y.Key, y.Value, calculationResult)); }
private static List<KeyValuePair<string, int>> OrderedWordsByValue(IDictionary<string, int> wordsCount) { List<KeyValuePair<string, int>> sorted = wordsCount.ToList(); sorted.Sort((firstPair, nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); } ); return sorted; }
internal static void MergeDifferentEntries <TKey, TValue>( this IDictionary <TKey, TValue> source, IDictionary <TKey, TValue> other) { other?.ToList().ForEach(x => { if (!source.ContainsKey(x.Key)) { source[x.Key] = x.Value; } }); }
public ReportRunner( ReportFormat reportFormat, string reportPath, IDictionary<string, object> reportParameters, ProcessingMode mode = ProcessingMode.Remote, IDictionary<string, DataTable> localReportDataSources = null) : this(reportFormat, reportPath, reportParameters != null ? reportParameters.ToList() : null, mode, localReportDataSources) { }
/// <summary> /// 上传数据 /// </summary> /// <param name="url"></param> /// <param name="service"></param> /// <param name="queries"></param> /// <param name="action"></param> /// <param name="failed"></param> protected void UploadString(string url , IDictionary<string, string> queries , Action<RestResponse, object> action , Action<Exception> failed , object userState) { bool httpResult = HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp); RestClient client = new RestClient(); client.Method = WebMethod.Post; queries.ToList().ForEach(o => client.AddParameter(o.Key, o.Value)); client.AddHeader("X-Requested-With", "xmlhttp"); client.Authority = url; RestRequest restRequest = new RestRequest(); CookieContainer cookieContainer = null; if (IsolatedStorageSettings.ApplicationSettings.Contains("cookie")) { cookieContainer = IsolatedStorageSettings.ApplicationSettings["cookieContainer"] as CookieContainer; Cookie cookie = IsolatedStorageSettings.ApplicationSettings["cookie"] as Cookie; if (cookieContainer.Count == 0 && cookie != null) { cookieContainer.SetCookies(new Uri(Constant.ROOTURL), string.Format("{0}={1}", cookie.Name, cookie.Value)); } } else { cookieContainer = new CookieContainer(); } restRequest.CookieContainer = cookieContainer; client.BeginRequest(restRequest, (request, response, userState1) => { cookieContainer = response.CookieContainer; CookieCollection cookies = cookieContainer.GetCookies(new Uri(Constant.ROOTURL)); try { IsolatedStorageSettings.ApplicationSettings["cookie"] = cookies["cooper"]; IsolatedStorageSettings.ApplicationSettings["cookieContainer"] = cookieContainer; IsolatedStorageSettings.ApplicationSettings.Save(); } catch { } if (response != null) Deployment.Current.Dispatcher.BeginInvoke(action, response, userState1); else Deployment.Current.Dispatcher.BeginInvoke(failed, new Exception("response返回为空!")); }, userState); }
public void InitValues(IDictionary<string, object> defaultValues) { valueControls.Clear(); items.Children.Clear(); items.RowDefinitions.Clear(); var defVals = defaultValues.ToList(); for (int i = 0; i < defVals.Count; ++i) { var p = defVals[i]; items.RowDefinitions.Add(new RowDefinition()); var control = CreateItem(p.Key, p.Value, i, items); valueControls.Add(p.Key, new Tuple<Control, Type>(control, p.Value.GetType())); } }
public ReportRunner( ReportFormat reportFormat, string reportPath, string reportServerUrl, string username, string password, IDictionary<string, object> reportParameters) : this(reportFormat, reportPath, reportServerUrl, username, password, reportParameters != null ? reportParameters.ToList() : null) { }
public static IDictionary <T1, T2> Merge <T1, T2>(this IDictionary <T1, T2> first, IDictionary <T1, T2> second) { if (first == null) { throw new ArgumentNullException("first"); } if (second == null) { throw new ArgumentNullException("second"); } var merged = new Dictionary <T1, T2>(); first.ToList().ForEach(kv => merged[kv.Key] = kv.Value); second.ToList().ForEach(kv => merged[kv.Key] = kv.Value); return(merged); }
public static string ToString <K, V>(this IDictionary <K, V> arr, char seperator = ',') { StringBuilder sb = new StringBuilder(); var list = arr.ToList(); for (int i = 0; i <= list.Count - 1; i++) { sb.Append(list[i].Key).Append('=').Append(list[i].Value); if (i != list.Count - 1) { sb.Append(seperator); } } return(sb.ToString()); }
static void LogEvent(string eventName, IDictionary<string, object> eventData = null) { var dict = GetGenericEventDict(); if (eventData != null) { var dataList = eventData.ToList(); dataList.ForEach(pair => { dict.Add(pair); }); } Analytics.CustomEvent(eventName, dict); }
/// <summary> /// Update method. /// </summary> /// <param name="gameTime">Snapshot of elapsed time values.</param> public void Update(GameTime gameTime) { // Check if there are entities to load. if (entities.Count > 0) { // Get entities. IReadOnlyList <KeyValuePair <int, ILoadable> > loadables = entities.ToList(); // Load entity and remove from map. foreach (KeyValuePair <int, ILoadable> loadable in loadables) { loadable.Value.Load(contentManager); RemoveEntity(loadable.Key); } } }
public MovedBlockState(IDictionary <string, IDoor> doors) { foreach (KeyValuePair <string, IDoor> door in doors.ToList()) { if (door.Key == "left" && door.Value is LeftOther) { doors.Remove("left"); doors.Add("left", new LeftOpen()); } if (door.Key == "right" && door.Value is RightOther) { doors.Remove("right"); doors.Add("right", new RightOpen()); } } }
public void IDictionary_Generic_Values_IncludeDuplicatesMultipleTimes(int count) { IDictionary <TKey, TValue> dictionary = GenericIDictionaryFactory(count); int seed = 431; foreach (KeyValuePair <TKey, TValue> pair in dictionary.ToList()) { TKey missingKey = CreateTKey(seed++); while (dictionary.ContainsKey(missingKey)) { missingKey = CreateTKey(seed++); } dictionary.Add(missingKey, pair.Value); } Assert.Equal(count * 2, dictionary.Values.Count); }
/// <summary> /// Iterates through the elements in a clone of the given dictionary. /// This method is safe, the dictionary can be manipulated by the action without causing "out of range", or "collection modified" exceptions. /// </summary> public static void ForEach <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, Action <TKey, TValue> action) { if (dictionary == null || dictionary.Count == 0 || action == null) { return; } var arr = dictionary.ToList(); foreach (var kvp in arr) { action(kvp.Key, kvp.Value); } Free(arr, true); }
public static void ForEach <TKey, TValue>(IDictionary <TKey, TValue> dictionary, Action <TKey, TValue> action) { if (dictionary == null || dictionary.Count == 0 || action == null) { return; } List <KeyValuePair <TKey, TValue> > l = dictionary.ToList(); foreach (KeyValuePair <TKey, TValue> kvp in l) { action(kvp.Key, kvp.Value); } Free(l); }
public ReportRunner( ReportFormat reportFormat, string reportPath, IDictionary <string, object> reportParameters, ProcessingMode mode = ProcessingMode.Remote, IDictionary <string, DataTable> localReportDataSources = null, string filename = null) : this( reportFormat, reportPath, reportParameters?.ToList(), mode, localReportDataSources, filename) { }
/// <summary> /// Iterates through the elements in a clone of the given collection. /// This method is safe, the list can be manipulated by the action without causing "out of range", or "collection modified" exceptions. /// </summary> public static void For <TKey, TValue>(this IDictionary <TKey, TValue> list, Action <int, TKey, TValue> action) { if (list == null || action == null) { return; } var arr = list.ToList(); for (int i = 0; i < arr.Count; i++) { action(i, arr[i].Key, arr[i].Value); } Free(arr, true); }
public static void For <TKey, TValue>(IDictionary <TKey, TValue> list, Action <int, TKey, TValue> action) { if (list == null || action == null) { return; } List <KeyValuePair <TKey, TValue> > l = list.ToList(); for (int i = 0; i < l.Count; i++) { action(i, l[i].Key, l[i].Value); } Free(l); }
/// <summary> /// Excutes and also verifies the results with expected values. /// </summary> /// <param name="variables"> /// A <see cref="IDictionary{TKey,TValue}"/> of variables. /// </param> public void ExecuteAndVerify(IDictionary <string, object> variables) { IDictionary <string, object> previousTestResults = new Dictionary <string, object>(); IDictionary <string, object> allVariables = new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase); variables.ToList().ForEach(kv => allVariables[kv.Key] = kv.Value); foreach (var test in this._tests) { try { if (test.Variables != null) { var testVariables = this.EvaluateParameters(test.Variables, allVariables); // merge these into all variables testVariables.ToList().ForEach(kv => allVariables[kv.Key] = kv.Value); } if (!string.IsNullOrWhiteSpace(test.Api)) { var results = this.ExecuteTest(test, allVariables, previousTestResults, out var resultsType); previousTestResults["result"] = results; this.VerifyResults(test, resultsType, results, allVariables); if (test.Extracts != null) { allVariables["result"] = results; var extractVariables = this.EvaluateParameters(test.Extracts, allVariables); extractVariables.ToList().ForEach(kv => allVariables[kv.Key] = kv.Value); } } } catch (Exception e) { var expectedObjectJson = JsonConvert.DeserializeObject <ExpectedExceptionInfo>( JsonConvert.SerializeObject(test.GetExpectedResults())); if (expectedObjectJson.Exception) { this.VerifyException(test, expectedObjectJson, e); } else { throw; } } } }
void SendData(string currentURL, string pageTitle, string methodName, IDictionary <string, long> advancedValues) { // set the data. List <string> entryPath = CreatePath(currentURL, pageTitle, conf); EntryBuilder ebNormal = new EntryBuilder(entryPath, startTime); ebNormal.Url = currentURL; ebNormal.Status = Statuses.NewStatus(methodName, exception); double value = Time.CurrentTimeMillis() - startTime; ebNormal.Value = value; ebNormal.Unit = TimerBuilder.DefaultUnit; List <Entry> entriesToSend = new List <Entry>(); entriesToSend.Add(ebNormal.Build()); foreach (KeyValuePair <string, long> pair in advancedValues.ToList()) { List <string> advancedPath = new List <string>(entryPath); string[] pathEntries = pair.Key.Split('/'); advancedPath.AddRange(pathEntries); EntryBuilder ebAdv = new EntryBuilder(advancedPath, startTime); ebAdv.Url = currentURL; ebAdv.Status = Statuses.NewStatus(methodName, exception); ebAdv.Value = value; ebAdv.Unit = TimerBuilder.DefaultUnit; ebAdv.Value = pair.Value; entriesToSend.Add(ebAdv.Build()); } if (isDebug) { foreach (Entry entry in entriesToSend) { Logger.GetLogger().DebugMessage("Sending entry. URL: " + currentURL + ", Title: " + pageTitle + ", Entry: " + entry); } } // send the data. dataExchangeAPIClient.AddEntries(entriesToSend); }
private string RenderAttributes(IDictionary<string, object> htmlAttributes) { if (null == htmlAttributes) throw new ArgumentNullException("htmlAttributes"); var attributes = string.Empty; htmlAttributes.ToList().ForEach(pair => { var key = pair.Key; var value = pair.Value; attributes += ( value == null ? string.Format("{0} ", HttpUtility.HtmlEncode(key)) : string.Format("{0}=\"{1}\" ", HttpUtility.HtmlEncode(key), HttpUtility.HtmlAttributeEncode(value.ToString())) ); }); return attributes.Trim(); }
public async static Task <byte[]> GetBytesAsync(string url, IDictionary <string, string> headers = null) { using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url)) { //添加http请求头 headers?.ToList().ForEach(item => { request.Headers.Add(item.Key, item.Value); }); using (HttpResponseMessage response = await httpClient.SendAsync(request)) { response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsByteArrayAsync()); } } }
/// <summary> /// Compute cluster health /// </summary> protected virtual void ComputeClusterHealth() { var clusterHealth = new ClusterHealth(); foreach (var performanceCounter in _performanceCounters.ToList()) { if (!clusterHealth.PerformanceCounters.ContainsKey(performanceCounter.Key) && !clusterHealth.PerformanceCounters.TryAdd(performanceCounter.Key, Convert.ToInt64(performanceCounter.Value))) { Logger.LogWarning($"Could not add performance counter {performanceCounter.Key}."); } } ClusterMetrics.Health = clusterHealth; var clusterMetricSubmitted = ClusterMetricSubmitted; clusterMetricSubmitted?.Invoke(this, new ClusterMetricsEventArgs(ClusterMetrics)); }
public static string Dump(string sql, IDictionary <string, object> parameters, ISqlDialect dialect = null) { if (parameters == null) { return(sql); } var param = parameters.ToList(); for (var i = 0; i < param.Count; i++) { var name = param[i].Key; if (!name.StartsWith("@")) { param[i] = new KeyValuePair <string, object>("@" + name, param[i].Value); } } param.Sort((x, y) => y.Key.Length.CompareTo(x.Key.Length)); var sb = new StringBuilder(sql); foreach (var pair in param) { sb.Replace(pair.Key, DumpParameterValue(pair.Value, dialect)); } var text = DatabaseCaretReferences.Replace(sb.ToString()); dialect = dialect ?? SqlSettings.DefaultDialect; var openBracket = dialect.OpenQuote; if (openBracket != '[') { text = BracketLocator.ReplaceBrackets(text, dialect); } var paramPrefix = dialect.ParameterPrefix; if (paramPrefix != '@') { text = ParamPrefixReplacer.Replace(text, paramPrefix); } return(text); }
protected virtual IDictionary<string, string> ReadConfiguration(IDataReader reader, IDictionary<string, string> config) { bool any = false; while (reader.Read()) { var key = reader[Settings.KeyField]; var value = reader[Settings.ValueField]; if (key == DBNull.Value || value == DBNull.Value) continue; any = true; config[key.ToString()] = value.ToString(); } if (!any) return config; List<KeyValuePair<string, string>> list = config.ToList(); list.Sort((firstPair, nextPair) => nextPair.Key.Length.CompareTo(firstPair.Key.Length)); return list.ToDictionary(pair => pair.Key, pair => pair.Value); }
public void AddToContext(IDictionary <string, string> properties) { if (properties != null) { if (_contextProperties == null) { _contextProperties = new ConcurrentDictionary <string, string>(); } properties.ToList().ForEach(x => { if (!_contextProperties.ContainsKey(x.Key)) { _contextProperties.Add(x.Key, x.Value); } }); } }
public void InitValues(IDictionary <string, object> defaultValues) { valueControls.Clear(); items.Children.Clear(); items.RowDefinitions.Clear(); var defVals = defaultValues.ToList(); for (int i = 0; i < defVals.Count; ++i) { var p = defVals[i]; items.RowDefinitions.Add(new RowDefinition()); var control = CreateItem(p.Key, p.Value, i, items); valueControls.Add(p.Key, new Tuple <Control, Type>(control, p.Value.GetType())); } }
public static string ReplaceTokens(string html, IDictionary <string, string> data) { data.ToList().ForEach(d => { var key = d.Key; // pad if [[ ]] aren't there if (!key.StartsWith("[[") || !key.EndsWith("]]")) { key = "[[" + key + "]]"; } html = html.Replace(key, d.Value); }); return(html); }
public async Task <TResponse> CallHttpMethod <TResponse, TRequest>(string baseAddress, string uri, TRequest request, IDictionary <string, string> headers, HttpMethods method) { using (var client = new System.Net.Http.HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.BaseAddress = new Uri(baseAddress); var endpointUri = new Uri(uri); headers.ToList().ForEach(x => client.DefaultRequestHeaders.Add(x.Key, x.Value)); var response = await InvokeHttpCall(method, request, client, endpointUri); return(await HandleResponse <TResponse, TRequest>(response)); } }
/// <summary> /// Substitutes the given name/values into the expression. /// </summary> public string Substitute(IDictionary <string, string> values) { Guard.NotNull(() => values, values); string expression = Expression; values.ToList() .ForEach(val => { if (Substitutions.Contains(val.Key)) { expression = expression.Replace(val.Key, val.Value); } }); return(expression); }
private async Task <HostResult> doAction(string[] args) { var options = Args.InvokeAction <ProcessorArgs>(args); using (var hostFileStream = new FileStream(hostFilePath, FileMode.Truncate)) { using (var writer = new StreamWriter(hostFileStream)) { Hosts.ToList().ForEach(async(pair) => await writer .WriteLineAsync(string.Format("{0} {1}", pair.Value, pair.Key))); } } var baseArgs = (options.ActionArgs as BaseActionArgs); return(baseArgs.Result); }
/// <summary> /// 查找所有符合条件的对象集合 /// </summary> /// <param name="condition">key-value条件</param> /// <param name="sortList">排序的属性</param> /// <typeparam name="T">文档对象类型</typeparam> /// <returns>查找到的集合</returns> public List <T> FindByCondition <T>(IDictionary <string, object> condition, IDictionary <string, bool> sortList) where T : IDocumentEntity, new() { var result = Excute(() => { var collection = GetCollection <T>(); var query = collection.Find(new QueryDocument(condition)); sortList.ToList().ForEach(p => query = query.SetSortOrder(new SortByDocument(p.Key, new BsonInt32(p.Value ? 1 : -1)))); return(query.ToList()); }); if (AutoLoadNavProperty) { LoadNavProperty(result); } return(result); }
/// <summary> /// Merges two dictionaries /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dictionary"></param> /// <param name="source"></param> public static void Merge <T>(this IDictionary <string, T> target, IDictionary <string, T> source) { if (source != null) { source.ToList().ForEach(x => { if (target.ContainsKey(x.Key)) { target[x.Key] = x.Value; } else { target.Add(x.Key, x.Value); } }); } }
/// <summary> /// Substitutes the given name/values into the expression. /// </summary> private string Substitute(IDictionary <string, string> values) { values.GuardAgainstNull(nameof(values)); var expression = Expression; values.ToList() .ForEach(val => { if (Substitutions.Contains(val.Key)) { expression = expression.Replace(val.Key, val.Value); } }); return(expression); }
public void AddRange(IDictionary <TKey, TValue> items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } if (items.Any()) { foreach (var item in items) { Dictionary.Add(item); } OnCollectionChanged(NotifyCollectionChangedAction.Add, items.ToList()); } }
public static T DeSerializeObjectFromXmlFile <T>(string content, IDictionary <String, String> namespaceCollection) { if (string.IsNullOrEmpty(content)) { return(default(T)); } T objectOut = default(T); string attributeXml = string.Empty; XmlDocument xmlDocument = new XmlDocument(); NameTable nt = new NameTable(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt); namespaceCollection.ToList().ForEach(item => { nsmgr.AddNamespace(item.Key, item.Value); }); XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); XmlReaderSettings xset = new XmlReaderSettings(); xset.ConformanceLevel = ConformanceLevel.Fragment; XmlReader rd = XmlReader.Create(new StringReader(content), xset, context); xmlDocument.Load(rd); string xmlString = xmlDocument.OuterXml; using (StringReader read = new StringReader(xmlString)) { Type outType = typeof(T); XmlSerializer serializer = new XmlSerializer(outType); using (XmlReader reader = new XmlTextReader(read)) { objectOut = (T)serializer.Deserialize(reader); reader.Close(); } read.Close(); } return(objectOut); }
public string Transform(string template, TemplateFormat format, IDictionary<string, object> data) { var result = template; var entries = data.ToList(); foreach(var kv in entries) { //Quick check without braces/tags if(!result.Contains(kv.Key)) continue; var tag = OpenTag + kv.Key + EndTag; var strValue = kv.Value + string.Empty; //safe ToString() if(!string.IsNullOrWhiteSpace(strValue) && format == TemplateFormat.Html) strValue = StringHelper.EscapeForHtml(strValue); result = result.Replace(tag, strValue); } if(result.Contains(EscapedOpenTag)) result = result.Replace(EscapedOpenTag, OpenTag); return result; }
public static void PublishWorkflow(this WorkflowManagementClient client, string workflowName, string xamlFilePath, Collection<ExternalVariable> externalVariables, IDictionary<string, string> configValues, SubscriptionFilter activationFilter = null) { // publish the activity description related with the workflow client.Activities.Publish( new ActivityDescription(WorkflowUtils.Translate(xamlFilePath)) { Name = workflowName },true,true); // now, publish the workflow description WorkflowDescription description = new WorkflowDescription { Name = workflowName, ActivityPath = workflowName, }; // add external variables if (externalVariables != null) { externalVariables .ToList() .ForEach(ev => description.ExternalVariables.Add(ev)); } // add config if (configValues != null) { description.Configuration = new WorkflowConfiguration(); configValues .ToList() .ForEach(c => description.Configuration.AppSettings.Add(c)); } // add activation filter if (activationFilter != null) { description.ActivationDescription = new SubscriptionActivationDescription { Filter = activationFilter }; } // publish! client.Workflows.Publish(description); }
public static string Dump(string sql, IDictionary<string, object> parameters, ISqlDialect dialect = null) { if (parameters == null) return sql; var param = parameters.ToList(); for (var i = 0; i < param.Count; i++) { var name = param[i].Key; if (!name.StartsWith("@")) param[i] = new KeyValuePair<string,object>("@" + name, param[i].Value); } param.Sort((x, y) => y.Key.Length.CompareTo(x.Key.Length)); var sb = new StringBuilder(sql); foreach (var pair in param) sb.Replace(pair.Key, DumpParameterValue(pair.Value, dialect)); return sb.ToString(); }
public static async Task<string> Serialize(IDictionary<string, string[]> dictionary) { var dict = new Dictionary<string, string>(); foreach (var item in dictionary.ToList()) { if (item.Value != null) { var header = String.Empty; foreach (var value in item.Value) { header += value + " "; } // Trim the trailing space and add item to the dictionary header = header.TrimEnd(" ".ToCharArray()); dict.Add(item.Key, header); } } return await Task.Factory.StartNew(() => JsonConvert.SerializeObject(dict, Formatting.None)); }
/// <summary> /// This will go through a dictionary of strings (usually configuration values) and replace all tokens in that string /// with whatever the token-resolver delivers. It's usually needed to initialize a DataSource. /// </summary> /// <param name="configList">Dictionary of configuration strings</param> /// <param name="instanceSpecificPropertyAccesses">Instance specific additional value-dictionaries</param> public void LoadConfiguration(IDictionary<string, string> configList, Dictionary<string, IValueProvider> instanceSpecificPropertyAccesses = null, int repeat = 2) { #region if there are instance-specific additional Property-Access objects, add them to the sources-list // note: it's important to create a one-time use list of sources if instance-specific sources are needed, to never modify the "global" list. var useAdditionalPA = (instanceSpecificPropertyAccesses != null); // not null, so it has instance specific stuff if (useAdditionalPA) foreach (var pa in Sources) if (!instanceSpecificPropertyAccesses.ContainsKey(pa.Key)) instanceSpecificPropertyAccesses.Add(pa.Key.ToLower(), pa.Value); var instanceTokenReplace = useAdditionalPA ? new TokenReplace(instanceSpecificPropertyAccesses) : _reusableTokenReplace; #endregion #region Loop through all config-items and token-replace them foreach (var o in configList.ToList()) { // check if the string contains a token or not if (!TokenReplace.ContainsTokens(o.Value)) continue; configList[o.Key] = instanceTokenReplace.ReplaceTokens(o.Value, repeat); // with 2 further recurrances } #endregion }
public void UpdateDataFields(Guid processId, IDictionary<string, string> overrides) { var process = this.GetProcessById(processId); if (overrides != null) overrides.ToList().ForEach(o => process.UpdateDataField(o.Key, o.Value)); this._processService.Update(process); }
internal Invoker(string name, Type[] genericParameters, Type[] genericMethodParameters, ExtensionToInstanceProxy parent, Type[] overloadTypes = null) { Name = name; Parent = parent; GenericParams = genericParameters; GenericMethodParameters = genericMethodParameters; OverloadTypes = new Dictionary<int,Type[]>(); if (overloadTypes == null) { foreach (var tGenInterface in parent.InstanceHints) { var tNewType = tGenInterface; if (tNewType.IsGenericType) { tNewType = tNewType.MakeGenericType(GenericParams); } var members = tNewType.GetMethods(BindingFlags.Instance | BindingFlags.Public).Where( it => it.Name == Name).ToList(); foreach (var tMethodInfo in members) { var tParams = tMethodInfo.GetParameters().Select(it => it.ParameterType).ToArray(); if (OverloadTypes.ContainsKey(tParams.Length)) { OverloadTypes[tParams.Length] = new Type[] {}; } else { OverloadTypes[tParams.Length] = tParams.Select(ReplaceGenericTypes).ToArray(); } } foreach (var tOverloadType in OverloadTypes.ToList()) { if (tOverloadType.Value.Length == 0) { OverloadTypes.Remove(tOverloadType); } } } } else { OverloadTypes[overloadTypes.Length] = overloadTypes; } }
public static void Send(Base.VW.IWISV WI, IDictionary<ushort, ImperialRightSemaphore> lookup, ImperialRightSemaphore live) { lookup.ToList().ForEach(p => p.Value.Telegraph(q => WI.Send(q, 0, p.Key))); live.Telegraph(WI.Live); }
private static bool ExpandExpressions(IDictionary<string, string> target, IDictionary<string, string> lookup) { var temp = target.ToList(); return temp.Count(pair => ExpandExpression(pair, target, lookup)) > 0; }
public static void ToSortedFile(IDictionary<string, int> map, string path) { var list = map.ToList(); list.Sort((first, next) => next.Value.CompareTo(first.Value)); var text = list.Select(x => x.Key + "\t" + x.Value); File.WriteAllLines(path, text); }
public static void AddParameters(this IDbCommand command, IDictionary<string, object> parametersData) { parametersData.ToList().ForEach(command.AddParameter); }
/// <summary> /// Creates an instance of MvcReportViewerIframe class. /// </summary> /// <param name="reportPath">The path to the report on the server.</param> /// <param name="reportServerUrl">The URL for the report server.</param> /// <param name="username">The report server username.</param> /// <param name="password">The report server password.</param> /// <param name="reportParameters">The report parameter properties for the report.</param> /// <param name="controlSettings">The Report Viewer control's UI settings.</param> /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param> /// <param name="method">Method for sending parameters to the iframe, either GET or POST.</param> public MvcReportViewerIframe( IReportLoader reportLoader, IDictionary<string, object> reportParameters, ControlSettings controlSettings, IDictionary<string, object> htmlAttributes, FormMethod method) { var javaScriptApi = ConfigurationManager.AppSettings[WebConfigSettings.JavaScriptApi]; if (string.IsNullOrEmpty(javaScriptApi)) { throw new MvcReportViewerException("MvcReportViewer.js location is not found. Make sure you have MvcReportViewer.AspxViewerJavaScript in your Web.config."); } _reportLoader = reportLoader; _processingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local; _controlSettings = controlSettings; _reportParameters = reportParameters != null ? reportParameters.ToList() : null; _htmlAttributes = htmlAttributes; _method = method; _aspxViewer = ConfigurationManager.AppSettings[WebConfigSettings.AspxViewer]; if (string.IsNullOrEmpty(_aspxViewer)) { throw new MvcReportViewerException("ASP.NET Web Forms viewer is not set. Make sure you have MvcReportViewer.AspxViewer in your Web.config."); } _aspxViewer = _aspxViewer.Trim(); if (_aspxViewer.StartsWith("~")) { _aspxViewer = VirtualPathUtility.ToAbsolute(_aspxViewer); } var encryptParametesConfig = ConfigurationManager.AppSettings[WebConfigSettings.EncryptParameters]; if (!bool.TryParse(encryptParametesConfig, out _encryptParameters)) { _encryptParameters = false; } ControlId = Guid.NewGuid(); }