/// <summary> /// Returns an HTML dropdown list /// additional view data. If the user does not have edit right it is disabled. /// </summary> /// <param name="html"></param> /// <param name="expression"></param> /// <param name="attributes"></param> /// <returns></returns> public static IHtmlString CustomDropDownList <TModel, TProperty>(this HtmlHelper <TModel> html, Expression <Func <TModel, TProperty> > expression, IDictionary <string, object> attributes = null) { List <Right> rights = html.GetRights(); IDictionary <string, object> htmlAttributes = new Dictionary <string, object> { ["ng-model"] = expression.Body.ToString() }; attributes?.ForEach(a => htmlAttributes.Add(a)); if (typeof(TProperty) != typeof(string)) { htmlAttributes.Add("convert-to-number", "convert-to-number"); } if (!htmlAttributes.ContainsKey("disabled")) { if (rights == null || html.IsEditMode() && !rights.Any(r => r != null && r.Edit) || !html.IsEditMode() && !rights.Any(r => r != null && r.Create)) { htmlAttributes.Add("disabled", "disabled"); } } if (expression.IsRequired()) { htmlAttributes.Add("required", "required"); } string propertyName = expression.Body.ToString(); propertyName = propertyName.Substring(propertyName.IndexOf('.') + 1); return(html.DropDownList(propertyName, null, string.Empty, htmlAttributes)); }
private void CreateLegacyGSDKConfigFile(int instanceNumber, string sessionHostUniqueId, Dictionary <string, string> certThumbprints, IDictionary <string, string> portMappings) { // Legacy games are currently assumed to have only 1 asset.zip file which will have the game.exe as well // as the assets. We just place ServiceDefinition.json in that folder itself (since it contains game.exe). // This assumption will change later on and the code below will need to adapt. string configFilePath = Path.Combine(VmConfiguration.GetAssetExtractionFolderPathForSessionHost(instanceNumber, 0), "ServiceDefinition.json"); ServiceDefinition serviceDefinition; if (_systemOperations.FileExists(configFilePath)) { _logger.LogInformation($"Parsing the existing service definition file at {configFilePath}."); serviceDefinition = JsonConvert.DeserializeObject <ServiceDefinition>(File.ReadAllText(configFilePath)); serviceDefinition.JsonWorkerRole = serviceDefinition.JsonWorkerRole ?? new JsonWorkerRole(); } else { _logger.LogInformation($"Creating the service definition file at {configFilePath}."); serviceDefinition = new ServiceDefinition { JsonWorkerRole = new JsonWorkerRole() }; } SetUpLegacyConfigValues(serviceDefinition, sessionHostUniqueId, instanceNumber, GetVmAgentIpAddress()); certThumbprints?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value)); portMappings?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value)); _sessionHostsStartInfo.DeploymentMetadata?.ForEach(x => serviceDefinition.JsonWorkerRole.SetConfigValue(x.Key, x.Value)); string outputJson = JsonConvert.SerializeObject(serviceDefinition, Formatting.Indented, CommonSettings.JsonSerializerSettings); // This will overwrite the file if it was already there (which would happen when restarting containers for the same assignment) _systemOperations.FileWriteAllText(configFilePath, outputJson); }
/// <summary> /// Formats the string with parameters of double braces (mustache-style - {{ }}) tokens /// </summary> /// <param name="string"></param> /// <param name="params"></param> /// <returns></returns> public static string Format(this string @string, IDictionary <string, object> @params) { var tokens = @string?.GetDoubleBracesTokens(); @params?.ForEach(kvp => tokens?.Where(token => token.Item2.IsEquals(kvp.Key)).ForEach(token => @string = @string?.Replace(StringComparison.OrdinalIgnoreCase, token.Item1, $"{kvp.Value}"))); return(@string); }
/// <summary> /// Finds the first node that match the given XPath query. /// </summary> /// <param name="xPathExpression">The XPath expression to use to locate the first node</param> /// <param name="namespaces">A list of namespaces and prefixes with which to query</param> /// <returns></returns> public IXmlProcessorNode FindFirst(string xPathExpression, IDictionary<string, string> namespaces) { Guard.NotNullOrEmpty(() => xPathExpression, xPathExpression); Guard.NotNull(() => namespaces, namespaces); if (!IsDocumentLoaded()) { throw new InvalidOperationException(Resources.XmlProcessor_ErrorLoadNotCalledFirst); } try { var nsManager = new XmlNamespaceManager(this.document.NameTable); namespaces.ForEach(ns => nsManager.AddNamespace(ns.Key, ns.Value)); var node = this.document.SelectSingleNode(xPathExpression, nsManager); if (node != null) { return new XmlProcessorNode(node); } return null; } catch (Exception ex) { throw new XPathException( string.Format(CultureInfo.CurrentCulture, Resources.XmlProcessor_ErrorXPathSearchFailed, xPathExpression), ex); } }
public static IObservable <UnityWebRequest> Put(string url, string body, IDictionary <string, string> headers = null, TimeSpan?timeout = null) { return(Observable.Defer(() => { var request = UnityWebRequest.Put(url, body); SetTimeout(request, timeout); headers?.ForEach(x => request.SetRequestHeader(x.Key, x.Value)); return Send(request); })); }
protected virtual void WriteJustifiedOutput(IDictionary<string, string> lines, int padding) { if (lines.Any()) { var totalPadding = lines.Max(l => l.Key.Length) + padding; lines.ForEach(a => WriteJustifiedItem(a.Key, a.Value, totalPadding)); Output.WriteLine(); } }
private ChomskyNormalFormTransformer(Variable startVariable, IDictionary<Variable, ICollection<IEnumerable<Symbol>>> rules) { _rules = new Dictionary<Variable, ICollection<IEnumerable<Symbol>>>(); rules.ForEach(p => { _rules.Add(p.Key, new List<IEnumerable<Symbol>>()); p.Value.ForEach(r => _rules[p.Key].Add(r)); }); _startVariable = GetNewVariableBasedOn(startVariable); AddRule(_startVariable, startVariable); }
/// <summary> /// Removes the specified recent history item. /// </summary> /// <param name="historyType">The history type.</param> /// <param name="values">The values necessary for loading the object as a dictionary of key value pairs.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="values"/> is <c>null</c> or empty.</exception> public void Remove(HistoryType historyType, IDictionary <string, object> values) { if (values == null || !values.Any()) { throw new ArgumentNullException("values"); } var key = new KeyModel("History").Add(historyType); values.ForEach(v => key.Add(v.Key.ToLower()).Add(v.Value)); UserService.Session.Remove(key); }
/// <summary> /// Tests whether the HTTP response message contains content headers provided by dictionary. /// </summary> /// <param name="headers">Dictionary containing content headers.</param> /// <returns>The same HTTP response message test builder.</returns> public IAndHttpResponseMessageTestBuilder ContainingContentHeaders( IDictionary <string, IEnumerable <string> > headers) { HttpResponseMessageValidator.ValidateContent(this.ActionResult.Content, this.ThrowNewHttpResponseMessageAssertionException); HttpResponseMessageValidator.ValidateHeadersCount( headers, this.ActionResult.Content.Headers, this.ThrowNewHttpResponseMessageAssertionException, isContentHeaders: true); headers.ForEach(h => this.ContainingContentHeader(h.Key, h.Value)); return(this); }
public TwitterOAuthClient(TwitterToken token, string endpoint, IDictionary<string, object> param = null) : base(token.Application.ConsumerKey, token.Application.ConsumerSecret, token.TokenKey, token.TokenSecret) { this.endpoint = token.Endpoints[endpoint]; var url = this.endpoint.Definition.Url; if (param != null) param.ForEach(kvp => url = url.Replace(kvp.Key, kvp.Value.ToString())); this.Url = url; this.MethodType = this.endpoint.Definition.MethodType == HttpMethod.Get ? MethodType.Get : MethodType.Post; }
public static void AddRange <K, V>(this IDictionary <K, V> dict, IDictionary <K, V> otherdict) { if (dict == null || otherdict == null) { return; } otherdict.ForEach(a => { if (!dict.ContainsKey(a.Key)) { dict.Add(a.Key, a.Value); } }); }
internal FFTText(Context context, IDictionary <Guid, ISerializableFile> files, QuickEdit quickEdit) { Filetype = context; List <IFile> filesList = new List <IFile>(files.Count + 1); files.ForEach(kvp => filesList.Add(kvp.Value)); filesList.Sort((a, b) => a.DisplayName.CompareTo(b.DisplayName)); if (quickEdit != null) { filesList.Insert(0, quickEdit); } Files = filesList.AsReadOnly(); CharMap = filesList[0].CharMap; }
public int insert_contact(IDictionary <string, object> columns, string status = null) { var insert = new InsertCommand(configuration); columns.ForEach(item => { insert.Contact[configuration.ColumnMap[item.Key]] = item.Value; }); if (!string.IsNullOrWhiteSpace(status)) { insert.Contact[ContactListConfiguration.Status] = status; } ContactListTransaction transaction = new ContactListTransaction(); transaction.Add(insert); return(configuration.RunTransaction(transaction)); }
public static List <T> ConvertAll <T, K, V>(IDictionary <K, V> map, Func <K, V, T> createFn) { var list = new List <T>(); #if !NETCF map.ForEach((kvp) => list.Add(createFn(kvp.Key, kvp.Value))); #else foreach (var key in map.Keys) { list.Add(createFn(key, map[key])); } #endif return(list); }
internal FFTText( Context context, IDictionary<Guid, ISerializableFile> files, IList<Glyph> customGlyphs, QuickEdit quickEdit ) { this.customGlyphs = customGlyphs; Filetype = context; List<IFile> filesList = new List<IFile>( files.Count + 1 ); files.ForEach( kvp => filesList.Add( kvp.Value ) ); filesList.Sort( ( a, b ) => a.DisplayName.CompareTo( b.DisplayName ) ); if (quickEdit != null) { filesList.Insert(0, quickEdit); } Files = filesList.AsReadOnly(); CharMap = filesList[0].CharMap; }
private static IDictionary <TKey, TValue> MakeDictionaryCopyOf <TKey, TValue>( IDictionary <TKey, TValue> src, Type targetType ) { var instance = Activator.CreateInstance(targetType) as IDictionary <TKey, TValue>; if (instance == null) { throw new InvalidOperationException($"Activator couldn't create instance of {targetType}"); } src?.ForEach(kvp => instance.Add(new KeyValuePair <TKey, TValue>(kvp.Key, kvp.Value))); return(instance); }
//modified version private static string ToQueryString2(IDictionary <string, object> dictionary, bool lowerCaseKey) { if (dictionary == null || dictionary.Count <= 0) { return(null); } var query = new StringBuilder(); if (lowerCaseKey) { dictionary.ForEach(d => query.AppendFormat("{0}={1}&", d.Key.ToLower(), d.Value)); } else { dictionary.ForEach(d => query.AppendFormat("{0}={1}&", d.Key, d.Value)); } if (query.Length > 0 && query[query.Length - 1] == '&') { query.Remove(query.Length - 1, 1); } return(query.ToString()); }
public void Test_For_Each_With_A_Dictionary() { IDictionary <string, string> dictionary = SampleDictionary(); IDictionary <string, string> expected = SampleDictionary(); ISet <string> keys = new HashSet <string>(); dictionary.ForEach((key, value) => { expected[key].Should().Be(value); keys.Add(key); }); expected.Keys.Should().Equal(keys); }
public void Begin( string status, IDictionary<string, string> headers ) { var builder = new DelimitedBuilder("\r\n"); var headerBuilder = new HeaderBuilder( headers ); builder.AppendFormat( "HTTP/1.1 {0}", status ); headers.ForEach( x => builder.AppendFormat( "{0}: {1}", x.Key, x.Value ) ); builder.Append( "\r\n" ); var header = builder.ToString(); var headerBuffer = Encoding.UTF8.GetBytes( header ); PendingWrite.Reset(); OnNext( new ArraySegment<byte>(headerBuffer), () => PendingWrite.Set() ); }
/// <summary> /// <para>Inserts the specified entities into the specified Table. Properties are matched</para> /// <para>with Sql Column Names by using the specified mappings dictionary.</para> /// </summary> /// <typeparam name="T">The type of entity to persist to Sql database.</typeparam> /// <param name="connection">This DbConnection.</param> /// <param name="entities">The entities to persist to Sql database.</param> /// <param name="tableName">The table to insert the entities into.</param> /// <param name="mappings"> /// <para>A Dictionary to use to map properties to Sql columns.</para> /// <para>Key = Property Name, Value = Sql Column Name.</para> /// </param> public static void InsertCollection <T>( this DbConnection connection, IEnumerable <T> entities, string tableName, IDictionary <string, string> mappings, Func <string, string> encloseIdentifier) { //using (var transactionScope = new TransactionScope()) //MySQL doesn't like this... //{ string fieldNames = mappings.Values.Select(x => encloseIdentifier(x)).Join(","); string parameterNames = mappings.Values.Join(",").Replace(",", ",@").Prepend("@"); var properties = typeof(T).GetProperties(); using (var command = connection.CreateCommand()) { string commandText = string.Format( INSERT_INTO_FORMAT, encloseIdentifier(tableName), fieldNames, parameterNames); command.CommandType = CommandType.Text; command.CommandText = commandText; mappings.ForEach(mapping => { var parameter = command.CreateParameter(); parameter.ParameterName = string.Concat("@", mapping.Value); var property = properties.Single(p => p.Name == mapping.Key); parameter.DbType = DataTypeConvertor.GetDbType(property.PropertyType); command.Parameters.Add(parameter); }); foreach (T entity in entities) { properties.ForEach(property => { command.Parameters["@" + property.Name].Value = property.GetValue(entity, null); //command.Parameters["@" + property.Name].Value = // GetFormattedValue(property.PropertyType, property.GetValue(entity, null)); }); command.ExecuteNonQuery(); } // transactionScope.Complete(); //} } }
/// <summary> /// Inserts [entities] into the specified table. The objects' property names are matched to column names /// by using the specified mappings dictionary. /// </summary> /// <typeparam name="T">The type of entity to persist to the database.</typeparam> /// <param name="connection">The DbConnection to use.</param> /// <param name="entities">The entities to persist to the database.</param> /// <param name="tableName">The name of the table to insert the entity into.</param> /// <param name="mappings"> /// A System.Collection.Generic.IDictionary`2 used to map object properties to column names. /// Key = Property Name, Value = Column Name. /// </param> /// <returns>The number of rows affected.</returns> public static int InsertCollection <T>(this DbConnection connection, IEnumerable <T> entities, string tableName, IDictionary <string, string> mappings) { const string INSERT_INTO_FORMAT = "INSERT INTO {0}({1}) VALUES({2})"; string fieldNames = mappings.Values.Join(","); string parameterNames = fieldNames.Replace(",", ",@").Prepend("@"); var properties = typeof(T).GetTypeInfo().GetProperties(); using (var command = connection.CreateCommand()) { string commandText = string.Format(INSERT_INTO_FORMAT, tableName, fieldNames, parameterNames); command.CommandType = CommandType.Text; command.CommandText = commandText; mappings.ForEach(mapping => { var parameter = command.CreateParameter(); parameter.ParameterName = string.Concat("@", mapping.Value); var property = properties.Single(p => p.Name == mapping.Key); parameter.DbType = DataTypeConvertor.GetDbType(property.PropertyType); command.Parameters.Add(parameter); }); bool alreadyOpen = (connection.State != ConnectionState.Closed); if (!alreadyOpen) { connection.Open(); } int rowsAffected = 0; foreach (var entity in entities) { properties.ForEach(property => { command.Parameters["@" + property.Name].Value = GetFormattedValue(property.PropertyType, property.GetValue(entity, null)); }); rowsAffected += command.ExecuteNonQuery(); } if (!alreadyOpen) { connection.Close(); } return(rowsAffected); } }
private void EnsureDbSeeded(IContext ctx) { _seedDict[typeof(Game)] = Seed.GetGames; _seedDict[typeof(Dice)] = Seed.GetDice; _seedDict[typeof(DiceWall)] = Seed.GetWalls; _seedDict[typeof(Config)] = Seed.GetConfigs; var info = GetType().GetMethod("InsertNotExisting", BindingFlags.Instance | BindingFlags.NonPublic); _seedDict.ForEach(pair => { var generic = info?.MakeGenericMethod(pair.Key); generic?.Invoke(this, new object[] { ctx }); }); }
public override async Task <TResult> ExecuteReader <TResult>(string commandText, IDictionary <string, object> parameters, Func <IDataReader, TResult> readerMapper) { using (var connection = await _connectionProvider.GetOpenConnection().ConfigureAwait(false)) using (var command = (SqliteCommand)connection.CreateCommand()) { command.CommandType = CommandType.Text; command.CommandText = commandText; parameters.ForEach(p => command.Parameters.Add(CreateParameter(p))); using (var reader = await command.ExecuteReaderAsync()) { return(readerMapper(reader)); } } }
/// <summary> /// Gets the recent history item for a specified history type and object ID /// </summary> /// <param name="historyType">The history type.</param> /// <param name="values">The values necessary for loading the object as a dictionary of key value pairs.</param> /// <returns>Returns <see cref="IEnumerable{HistoryModel}"/> for a single matching recent history record. If no matching record found returns null.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="values"/> is <c>null</c> or empty.</exception> public HistoryModel Get(HistoryType historyType, IDictionary <string, object> values) { if (values == null || !values.Any()) { throw new ArgumentNullException("values"); } var key = new KeyModel("History").Add(historyType); values.ForEach(v => key.Add(v.Key.ToLower()).Add(v.Value)); HistoryModel model; return((UserService.Session.TryGet(key, out model)) ? model : null); }
public static dynamic GetIronRubyRunitimeGlobals(IDictionary <string, object> variables, string fileToExecute) { var engine = Ruby.CreateEngine(); var scope = engine.CreateScope(); variables?.ForEach(v => scope.SetVariable(v.Key, v.Value)); if (!string.IsNullOrEmpty(fileToExecute)) { engine.ExecuteFile(fileToExecute, scope); } return(engine.Runtime.Globals); }
public static string Substitute(this IDictionary <string, string> subsitutions, string contentPlaceholders) { if (string.IsNullOrEmpty(contentPlaceholders)) { return(contentPlaceholders); } if (subsitutions == null || subsitutions.Count == 0) { return(contentPlaceholders); } string replacedValues = contentPlaceholders; subsitutions.ForEach((KeyValuePair <string, string> kv) => replacedValues = replacedValues.Replace("${" + kv.Key + "}", kv.Value)); return(replacedValues); }
/// <summary> /// 将字典对象转换为指定符号分隔字符串连接的字符串 /// </summary> /// <typeparam name="TKey">字典键类型</typeparam> /// <typeparam name="TValue">字典值类型</typeparam> /// <param name="dict">字典</param> /// <param name="itemSplit">字典项分隔符</param> /// <param name="keyValueSplit">字典名值对分隔符</param> /// <param name="reverse">是否反转字典名值对连接顺序(默认键连接值)</param> /// <returns>拼接后的字符串</returns> public static string Splice <TKey, TValue>(this IDictionary <TKey, TValue> dict, string itemSplit = "&", string keyValueSplit = "=", bool reverse = false) { if (dict == null) { return(string.Empty); } var items = new string[dict.Count()]; dict.ForEach((o, i) => { items[i] = !reverse ? string.Concat(o.Key, keyValueSplit, o.Value) : string.Concat(o.Value, keyValueSplit, o.Key); }); return(items.Splice(itemSplit)); }
public override async Task ExecuteNonQueryAsync(string commandText, IDictionary <string, object> parameters) { using (var connection = await _connectionProvider.GetOpenConnectionAsync().ConfigureAwait(false)) using (var command = (SqliteCommand)connection.CreateCommand()) { command.CommandType = CommandType.Text; EnableForeignKeys(command); command.CommandText = commandText; parameters.ForEach( parameter => command.Parameters.Add(new SqliteParameter(parameter.Key, parameter.Value ?? DBNull.Value))); await command.ExecuteNonQueryAsync().ConfigureAwait(false); } }
private static string ToQueryString(IDictionary <string, object> dictionary, bool lowerCaseKey) { if (dictionary == null || !dictionary.Any()) { return(null); } string query = string.Empty; dictionary.ForEach(d => { query += string.Format("{0}={1}&", lowerCaseKey ? d.Key.ToLower() : d.Key, d.Value); }); return(query.TrimEnd('&')); }
/// <summary> /// Builds a suffix tree. Every string is split into individual words, and each word associated with an <see cref="Node"/>. /// </summary> /// <param name="reader"></param> public Trie(IDictionary <byte[], HashSet <int> > reader) { Console.WriteLine("Building new tree from {0} words.", reader.Count()); Root = new Node(); reader.ForEach(kv => { BaseNode current = Root; int val = kv.Value.First(); foreach (byte b in kv.Key) { } kv.Key.ForEach(b => current.Add(b, val, out current)); //Build the branch using each byte as a node current?.End(val); //Mark the final node as a terminal }); Node.Loaded = true; }
public async Task <IViewComponentResult> InvokeAsync(string name, string sourceContextName, string controllerName, ICollection <TableColumnDefinition> tableDef, bool create = true, bool update = true, bool delete = true, object customRouteData = null, IDictionary <string, object> customViewData = null) { ViewData["name"] = CustomActionHelper.RandomName(name); ViewData["controllerName"] = controllerName; ViewData["create"] = create; ViewData["update"] = update; ViewData["delete"] = delete; ViewData["customRouteData"] = customRouteData; ViewData["contextForFk"] = sourceContextName; if (customViewData != null) { customViewData.ForEach(n => ViewData[n.Key] = n.Value); } return(View(tableDef)); }
/// <inheritdoc /> public IAndHttpResponseTestBuilder ContainingCookies(IDictionary <string, string> cookies) { var expectedCookiesCount = cookies.Count; var actualCookiesCount = this.GetAllCookies().Count; if (expectedCookiesCount != actualCookiesCount) { this.ThrowNewHttpResponseAssertionException( "cookies", $"to have {expectedCookiesCount} {(expectedCookiesCount != 1 ? "items" : "item")}", $"instead found {actualCookiesCount}"); } cookies.ForEach(c => this.ContainingCookie(c.Key, c.Value)); return(this); }
public IAndDistributedCacheTestBuilder ContainingEntries(IDictionary <string, string> entries) { var expectedItems = entries.Count; var actualItems = this.GetDistributedCacheMock().Count; if (expectedItems != actualItems) { this.ThrowNewDataProviderAssertionException( DistributedCacheName, $"to have {expectedItems} {(expectedItems != 1 ? "entries" : "entry")}", $"in fact found {actualItems}"); } entries.ForEach(e => this.ContainingEntry(e.Key, e.Value)); return(this); }
public override async Task <TKey> ExecuteScalarAsync <TKey>(string commandText, IDictionary <string, object> parameters) { using (var connection = await _connectionProvider.GetOpenConnectionAsync().ConfigureAwait(false)) using (var command = (SqliteCommand)connection.CreateCommand()) { command.CommandType = CommandType.Text; EnableForeignKeys(command); command.CommandText = commandText; parameters.ForEach( parameter => command.Parameters.Add(new SqliteParameter(parameter.Key, parameter.Value ?? DBNull.Value))); var result = await command.ExecuteScalarAsync().ConfigureAwait(false); if (typeof(TKey) == typeof(Guid)) { return((TKey)(object)new Guid((byte[])result)); } if (typeof(TKey) == typeof(int)) { if (result == null) { return((TKey)(object)0); } int retVal; if (!int.TryParse(result.ToString(), out retVal)) { return((TKey)(object)0); } return((TKey)(object)retVal); } if (typeof(TKey) == typeof(DateTime)) { DateTime retval; if (!DateTime.TryParse(result.ToString(), out retval)) { return((TKey)(object)DateTimeHelper.MinSqlValue); } return((TKey)(object)retval); } return((TKey)result); } }
public static FieldSetEntity ToFieldSet(this IDictionary <string, string> values) { var set = new FieldSetEntity { Id = 1 }; values.ForEach(kvp => set.Values.Add(new FieldSetValueEntity { FieldSetId = set.Id, Code = kvp.Key, Resource = new Dictionary <string, string> { { "en", kvp.Value } }.ToResource() })); return(set); }
private IList <PatchedByteArray> GetPspCharMapPatches(Stream iso, GenericCharMap baseCharmap, IDictionary <byte, string> dteInfo) { var pspIsoInfo = PspIso.PspIsoInfo.GetPspIsoInfo(iso); var dirEnt = DirectoryEntry.GetPspDirectoryEntries(iso, pspIsoInfo, PspIso.Sectors.PSP_GAME_USRDIR, 1); var currentEntry = dirEnt.Find(de => de.Filename == PspCharmapFileName); if (currentEntry != null) { dirEnt.Remove(currentEntry); } pspIsoInfo.RemoveFile(PspIso.Sectors.PSP_GAME_USRDIR_CHARMAP); var myDict = new Dictionary <int, string>(baseCharmap); dteInfo.ForEach(kvp => myDict[kvp.Key] = kvp.Value); System.Text.StringBuilder myString = new System.Text.StringBuilder(); myString.AppendLine(CharmapHeader); myDict.ForEach(kvp => myString.AppendFormat("{0:X4}\t{1}" + Environment.NewLine, kvp.Key, kvp.Value)); var bytes = System.Text.Encoding.UTF8.GetBytes(myString.ToString()); int insertSector = FindSectorToInsertPspCharmap(pspIsoInfo, bytes.Length); if (insertSector == -1) { throw new InvalidOperationException(); } pspIsoInfo.AddFile(PspIso.Sectors.PSP_GAME_USRDIR_CHARMAP, insertSector, bytes.Length); var baseDirEntry = dirEnt.Find(d => d.Filename == "fftpack.bin"); var charmapDirEntry = new PatcherLib.Iso.DirectoryEntry( (uint)insertSector, (uint)bytes.Length, DateTime.Now, baseDirEntry.GMTOffset, baseDirEntry.MiddleBytes, PspCharmapFileName, baseDirEntry.ExtendedBytes); AddOrReplaceCharMapDirectoryEntry(dirEnt, charmapDirEntry); var dirEntPatches = PatcherLib.Iso.DirectoryEntry.GetPspDirectoryEntryPatches( (int)PspIso.Sectors.PSP_GAME_USRDIR, 1, dirEnt); dirEntPatches.Add(new PatchedByteArray(PspIso.Sectors.PSP_GAME_USRDIR_CHARMAP, 0, bytes)); return(dirEntPatches); }
public int update_contact(DBColumn search_column, string key, IDictionary<string, object> new_values) { var update = new UpdateCommand(configuration, null); update.Where = new BinaryExpression(new ColumnExpression(search_column), new ConstantExpression(key, search_column), BinaryOperationType.Equal); new_values.ForEach(item => { update.UpdateData[configuration.ColumnMap[item.Key]] = item.Value; }); ContactListTransaction transaction = new ContactListTransaction(); transaction.Add(update); return configuration.RunTransaction(transaction); }
public void Save(IDictionary<CurrencyKey, CurrencyValue> values) { values.ForEach(x => Cache.GetOrAdd(x.Key, x.Value)); }
/// <summary> /// Sends a POST request with multipart/form-data. /// </summary> /// <returns>The response.</returns> /// <param name="url">URL.</param> /// <param name="prm">Parameters.</param> /// <param name="authorizationHeader">String of OAuth header.</param> /// <param name="userAgent">User-Agent header.</param> /// <param name="proxy">Proxy information for the request.</param> /// <param name="response">If it set false, won't try to get any responses and will return null.</param> internal static Stream HttpPostWithMultipartFormData(string url, IDictionary<string,object> prm, string authorizationHeader, string userAgent, IWebProxy proxy, bool response) { var boundary = Guid.NewGuid().ToString(); var req = (HttpWebRequest)WebRequest.Create(url); req.ServicePoint.Expect100Continue = false; req.Method = "POST"; req.UserAgent = userAgent; req.Proxy = proxy; req.ContentType = "multipart/form-data;boundary=" + boundary; req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader); using(var reqstr = req.GetRequestStream()) { Action<string> writeStr = s => { var bytes = Encoding.UTF8.GetBytes(s); reqstr.Write(bytes, 0, bytes.Length); }; prm.ForEach(x => { var valueStream = x.Value as Stream; var valueBytes = x.Value as IEnumerable<byte>; var valueFile = x.Value as FileInfo; var valueString = x.Value.ToString(); writeStr("--" + boundary + "\r\n"); if(valueStream != null || valueBytes != null || valueFile != null) writeStr("Content-Type: application/octet-stream\r\n"); writeStr(String.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key)); if(valueFile != null) writeStr(String.Format(@"; filename=""{0}""", valueFile.Name)); else if(valueStream != null || valueBytes != null) writeStr(@"; filename=""file"""); writeStr("\r\n\r\n"); if(valueFile != null) valueStream = valueFile.OpenRead(); if(valueStream != null) { while(true) { var buffer = new byte[4096]; var count = valueStream.Read(buffer, 0, buffer.Length); if (count == 0) break; reqstr.Write(buffer, 0, count); } } else if(valueBytes != null) valueBytes.ForEach(b => reqstr.WriteByte(b)); else writeStr(valueString); if(valueFile != null) valueStream.Close(); writeStr("\r\n"); }); writeStr("--" + boundary + "--"); } return response ? req.GetResponse().GetResponseStream() : null; }
private IList<PatchedByteArray> GetPspCharMapPatches( Stream iso, GenericCharMap baseCharmap, IDictionary<byte, string> dteInfo ) { var pspIsoInfo = PspIso.PspIsoInfo.GetPspIsoInfo( iso ); var dirEnt = DirectoryEntry.GetPspDirectoryEntries( iso, pspIsoInfo, PspIso.Sectors.PSP_GAME_USRDIR, 1 ); var currentEntry = dirEnt.Find( de => de.Filename == PspCharmapFileName ); if (currentEntry != null) { dirEnt.Remove( currentEntry ); } pspIsoInfo.RemoveFile( PspIso.Sectors.PSP_GAME_USRDIR_CHARMAP ); var myDict = new Dictionary<int, string>( baseCharmap ); dteInfo.ForEach( kvp => myDict[kvp.Key] = kvp.Value ); System.Text.StringBuilder myString = new System.Text.StringBuilder(); myString.AppendLine( CharmapHeader ); myDict.ForEach( kvp => myString.AppendFormat( "{0:X4}\t{1}" + Environment.NewLine, kvp.Key, kvp.Value ) ); var bytes = System.Text.Encoding.UTF8.GetBytes( myString.ToString() ); int insertSector = FindSectorToInsertPspCharmap( pspIsoInfo, bytes.Length ); if (insertSector == -1) { throw new InvalidOperationException(); } pspIsoInfo.AddFile( PspIso.Sectors.PSP_GAME_USRDIR_CHARMAP, insertSector, bytes.Length ); var baseDirEntry = dirEnt.Find( d => d.Filename == "fftpack.bin" ); var charmapDirEntry = new PatcherLib.Iso.DirectoryEntry( (uint)insertSector, (uint)bytes.Length, DateTime.Now, baseDirEntry.GMTOffset, baseDirEntry.MiddleBytes, PspCharmapFileName, baseDirEntry.ExtendedBytes ); AddOrReplaceCharMapDirectoryEntry( dirEnt, charmapDirEntry ); var dirEntPatches = PatcherLib.Iso.DirectoryEntry.GetPspDirectoryEntryPatches( (int)PspIso.Sectors.PSP_GAME_USRDIR, 1, dirEnt ); dirEntPatches.Add( new PatchedByteArray( PspIso.Sectors.PSP_GAME_USRDIR_CHARMAP, 0, bytes ) ); return dirEntPatches; }
HttpWebRequest http(IDictionary<string, string> headers) { var request = (HttpWebRequest)WebRequest.Create(_endPoint); request.Timeout = OPEN_TIMEOUT; request.ReadWriteTimeout = READ_TIMEOUT; request.ContentType = "text/xml"; headers.ForEach((name, value) => request.Headers.Add(name, value)); return request; }
/// <inheritdoc /> public IAndSessionBuilder WithEntries(IDictionary<string, string> entries) { entries.ForEach(e => this.WithEntry(e.Key, e.Value)); return this; }
/// <summary> /// Substitute the placeholders ${name} where name is the key in <paramref name="substitutions"/> /// and replace it with the value associated with the key. /// </summary> /// <param name="subsitutions"></param> /// <param name="contentPlaceholders"></param> /// <returns></returns> public static string Substitute(IDictionary<string, string> subsitutions, string contentPlaceholders) { if (string.IsNullOrEmpty(contentPlaceholders)) return contentPlaceholders; if (subsitutions == null || subsitutions.Count == 0) return contentPlaceholders; string replacedValues = contentPlaceholders; subsitutions.ForEach<KeyValuePair<string, string>>(kv => replacedValues = replacedValues.Replace("${" + kv.Key + "}", kv.Value)); return replacedValues; }
internal FFTText( Context context, IDictionary<Guid, ISerializableFile> files, QuickEdit quickEdit ) { Filetype = context; List<IFile> filesList = new List<IFile>( files.Count + 1 ); files.ForEach( kvp => filesList.Add( kvp.Value ) ); filesList.Sort( ( a, b ) => a.DisplayName.CompareTo( b.DisplayName ) ); filesList.Add( quickEdit ); Files = filesList.AsReadOnly(); CharMap = filesList[0].CharMap; }
public EDIXmlSegment GetLineItemInvoiceDetail(string lineNum, int quantity, decimal price, IDictionary<Qualifier, string> detail) { EdiXmlBuildValues buildValues = _buildFactory.GetValues(); var seg = new EDIXmlSegment("IT1", buildValues); seg.Add(new EDIXmlElement("IT101", lineNum, buildValues)); seg.Add(new EDIXmlElement("IT102", quantity.ToString(), buildValues)); seg.Add(new EDIXmlElement("IT103", "EA", buildValues)); seg.Add(new EDIXmlElement("IT104", price.ToString(), buildValues)); seg.Add(new EDIXmlElement("IT105","PE", buildValues)); int num = 6; detail.ForEach(p => add_invoice_detail(seg, p, buildValues, ref num) ); return seg; }
/// <summary> /// Imports the movies to the library /// </summary> /// <param name="movies"></param> public void Import(IDictionary<string, DateTime> movies) { movies.ForEach(pair => this.Add(this._factory.Create(pair.Key, pair.Value))); }
private static FormCollection GetForm(IDictionary<string, string> nameValues) { var form = new FormCollection(); nameValues.ForEach(kvp => form.Add(kvp.Key, kvp.Value)); return form; }
private IList<PatchedByteArray> GetPsxCharMapPatches( Stream iso, GenericCharMap baseCharmap, IDictionary<byte, string> dteInfo ) { var dirEnt = DirectoryEntry.GetPsxDirectoryEntries( iso, PsxRootDirEntSector, 1 ); var myDict = new Dictionary<int, string>( baseCharmap ); dteInfo.ForEach( kvp => myDict[kvp.Key] = kvp.Value ); System.Text.StringBuilder myString = new System.Text.StringBuilder(); myString.AppendLine( CharmapHeader ); myDict.ForEach( kvp => myString.AppendFormat( "{0:X4}\t{1}" + Environment.NewLine, kvp.Key, kvp.Value ) ); var bytes = System.Text.Encoding.UTF8.GetBytes( myString.ToString() ); var baseDirEntry = dirEnt.Find( d => d.Filename == "SCEAP.DAT;1" ); var charmapDirEntry = new PatcherLib.Iso.DirectoryEntry( PsxCharmapSector, (uint)bytes.Length, DateTime.Now, baseDirEntry.GMTOffset, baseDirEntry.MiddleBytes, PsxCharmapFileName, baseDirEntry.ExtendedBytes ); AddOrReplaceCharMapDirectoryEntry( dirEnt, charmapDirEntry ); var dirEntPatches = PatcherLib.Iso.DirectoryEntry.GetPsxDirectoryEntryPatches( PsxRootDirEntSector, 1, dirEnt ); dirEntPatches.Add( new PatchedByteArray( PsxCharmapSector, 0, bytes ) ); return dirEntPatches; }
public static void GetDataObject(Action<System.Net.WebClient> action, Uri uri, IWebClientCaller caller, IDictionary<string, string> queryParameters = null, IDictionary<string, string> headers = null) { NameValueCollection queryParams; if (queryParameters != null) { queryParams = new NameValueCollection(queryParameters.Count); queryParameters.ForEach(kvp => queryParams.Add(kvp.Key, kvp.Value)); } else { queryParams = new NameValueCollection(); } var headerParams = new WebHeaderCollection(); if (headers != null) headers.ForEach(kvp => headerParams.Add(kvp.Key, kvp.Value)); using (var client = new WebClientTimeouted(caller)) { client.Headers = headerParams; client.QueryString = queryParams; action(client); } }
/// <summary> /// Adds default collection of headers to every request tested on the server. /// </summary> /// <param name="headers">Dictionary of headers to add.</param> /// <returns>The same server builder.</returns> public IServerBuilder WithDefaultRequestHeaders(IDictionary<string, IEnumerable<string>> headers) { headers.ForEach(h => this.WithDefaultRequestHeader(h.Key, h.Value)); return this; }
public int insert_contact(IDictionary<string, object> columns, string status = null) { var insert = new InsertCommand(configuration); columns.ForEach(item => { insert.Contact[configuration.ColumnMap[item.Key]] = item.Value; }); if (!string.IsNullOrWhiteSpace(status)) { insert.Contact[ContactListConfiguration.Status] = status; } ContactListTransaction transaction = new ContactListTransaction(); transaction.Add(insert); return configuration.RunTransaction(transaction); }
IDictionary<Analysis, QonverterSettings> qonverterSettingsHandler (IDictionary<Analysis, QonverterSettings> oldSettings, out bool cancel) { qonverterSettingsByAnalysis = new Dictionary<Analysis, QonverterSettings>(); oldSettings.ForEach(o => qonverterSettingsByAnalysis.Add(o.Key, o.Value)); var result = UserDialog.Show(this, "Qonverter Settings", new QonverterSettingsByAnalysisControl(qonverterSettingsByAnalysis, showQonverterSettingsManager)); cancel = result == DialogResult.Cancel; return qonverterSettingsByAnalysis; }
/// <inheritdoc /> public IAndAuthenticationPropertiesTestBuilder WithItems(IDictionary<string, string> items) { this.validations.Add((expected, actual) => { var expectedItems = expected.Items.Count; var actualItems = actual.Items.Count - DefaultItemsCount; if (expectedItems != actualItems) { this.ThrowNewAuthenticationPropertiesAssertionException( $"have {expectedItems} custom {(expectedItems != 1 ? "items" : "item")}", $"in fact found {actualItems}"); } }); items.ForEach(item => this.WithItem(item.Key, item.Value)); return this; }
/// <inheritdoc /> public IAndMemoryCacheBuilder WithEntries(IDictionary<object, object> entries) { entries.ForEach(e => this.WithEntry(e.Key, e.Value)); return this; }
/// <inheritdoc /> public IAndTempDataBuilder WithEntries(IDictionary<string, object> entries) { entries.ForEach(e => this.WithEntry(e.Key, e.Value)); return this; }
/// <summary> /// Adds collection of content headers to the built HTTP request message. /// </summary> /// <param name="headers">Dictionary of headers to add.</param> /// <returns>The same HTTP request message builder.</returns> public IAndHttpRequestMessageBuilder WithContentHeaders(IDictionary<string, IEnumerable<string>> headers) { headers.ForEach(h => this.WithContentHeader(h.Key, h.Value)); return this; }
/// <summary> /// Adds collection of HTTP content headers to the built route test. /// </summary> /// <param name="headers">Dictionary of content headers to add.</param> /// <returns>The same route test builder.</returns> public IAndShouldMapTestBuilder WithContentHeaders(IDictionary<string, IEnumerable<string>> headers) { headers.ForEach(h => this.WithContentHeader(h.Key, h.Value)); return this; }
public static string EncodeObject(string key, IDictionary<string, SimpleType> values) { var list = new Dictionary<string, string>(values.Count); values.ForEach(kv => list.Add(Encode(kv.Key), Encode(kv.Value))); return FormatObject(Encode(key), list); }