public static string ToXml(IDictionary<string, object> dictionary, string elementName) { string attributes = dictionary.Where(kvp => kvp.Key.EndsWith(AttributeMarker)).Aggregate<KeyValuePair<string, object>, string>(null, (current, kvp) => current + string.Format(" {0}=\"{1}\"", kvp.Key.Replace(AttributeMarker, string.Empty), kvp.Value)); var stringBuilder = new StringBuilder("<{0}{1}>".Fmt(elementName, attributes)); foreach (var kvp in dictionary.Where(k => !k.Key.EndsWith(AttributeMarker))) { if (kvp.Value is IDictionary<string, object>) stringBuilder.Append(ToXml((IDictionary<string, object>)kvp.Value, kvp.Key)); else if (kvp.Value is dynamic[]) { foreach (var dyn in (dynamic[])kvp.Value) { stringBuilder.Append(ToXml(dyn, kvp.Key)); } } else if (kvp.Value.GetType().IsArray || (kvp.Value.GetType().IsGenericType && kvp.Value is IEnumerable)) { foreach (var value in (IEnumerable)kvp.Value) { stringBuilder.Append("<{0}>{1}</{0}>".Fmt(kvp.Key, value)); } } else stringBuilder.Append("<{0}>{1}</{0}>".Fmt(kvp.Key, kvp.Value)); } stringBuilder.Append("</{0}>".Fmt(elementName)); return stringBuilder.ToString(); }
public static string DictToQuerystring(IDictionary<string, string> qs) { return string.Join("&", qs .Where(k => !string.IsNullOrEmpty(k.Key)) .Select(k => string.Format("{0}={1}", HttpUtility.UrlEncode(k.Key), HttpUtility.UrlEncode(k.Value))) .ToArray()); }
public IDictionary<string, object> Insert(AdoAdapter adapter, string tableName, IDictionary<string, object> data, IDbTransaction transaction = null, bool resultRequired = false) { var table = adapter.GetSchema().FindTable(tableName); var insertData = data.Where(p => table.HasColumn(p.Key)).Select((kv, idx) => new InsertColumn { Name = kv.Key, ParameterName = "@p" + idx, Value = kv.Value, Column = (FbColumn) table.FindColumn(kv.Key) }).ToArray(); if (transaction == null) { using (var connection = adapter.ConnectionProvider.CreateConnection()) { connection.Open(); return CreateAndExecuteInsertCommand(connection, table, insertData, resultRequired); } } else { return CreateAndExecuteInsertCommand(transaction.Connection, table, insertData, resultRequired, transaction); } }
private static object ConvertValue(string elementName, BsonValue value, IDictionary<string, string> aliases) { if (value.IsBsonDocument) { aliases = aliases.Where(x => x.Key.StartsWith(elementName + ".")).ToDictionary(x => x.Key.Remove(0, elementName.Length + 1), x => x.Value); return value.AsBsonDocument.ToSimpleDictionary(aliases); } else if (value.IsBsonArray) return value.AsBsonArray.Select(v => ConvertValue(elementName, v, aliases)).ToList(); else if (value.IsBoolean) return value.AsBoolean; else if (value.IsDateTime) return value.AsDateTime; else if (value.IsDouble) return value.AsDouble; else if (value.IsGuid) return value.AsGuid; else if (value.IsInt32) return value.AsInt32; else if (value.IsInt64) return value.AsInt64; else if (value.IsObjectId) return value.AsObjectId; else if (value.IsString) return value.AsString; else if (value.BsonType == BsonType.Binary) return value.AsByteArray; return value.RawValue; }
private static ICollection<Claim> ClaimsFromJwt(IDictionary<string, object> jwtData, string issuer) { issuer = issuer ?? DefaultIssuer; var list = jwtData.Where(p => !claimsToExclude.Contains(p.Key)) // don't include specific claims .Select(p => new { Key = p.Key, Values = p.Value as JArray ?? new JArray { p.Value } }) // p.Value is either claim value of ArrayList of values .SelectMany(p => p.Values.Cast<object>() .Select(v => new Claim(p.Key, v.ToString(), StringClaimValueType, issuer, issuer))) .ToList(); // set claim for user name // use original jwtData because claimsToExclude filter has sub and otherwise it wouldn't be used var userNameClaimType = claimTypesForUserName.FirstOrDefault(ct => jwtData.ContainsKey(ct)); if (userNameClaimType != null) { list.Add(new Claim(NameClaimType, jwtData[userNameClaimType].ToString(), StringClaimValueType, issuer, issuer)); } // set claims for roles array list.Where(c => c.Type == "roles").ToList().ForEach(r => { list.Add(new Claim(RoleClaimType, r.Value, StringClaimValueType, issuer, issuer)); }); list.RemoveAll(c => c.Type == "roles"); return list; }
private IDictionary<string, object> Upsert(string tableName, IDictionary<string, object> data, SimpleExpression criteria, bool resultRequired, IDbConnection connection) { var finder = _transaction == null ? new AdoAdapterFinder(_adapter, connection) : new AdoAdapterFinder(_adapter, _transaction); var existing = finder.FindOne(tableName, criteria); if (existing != null) { // Don't update columns used as criteria var keys = criteria.GetOperandsOfType<ObjectReference>().Select(o => o.GetName().Homogenize()); var updateData = data.Where(kvp => keys.All(k => k != kvp.Key.Homogenize())).ToDictionary(); if (updateData.Count == 0) { return existing; } var commandBuilder = new UpdateHelper(_adapter.GetSchema()).GetUpdateCommand(tableName, updateData, criteria); if (_transaction == null) { _adapter.Execute(commandBuilder, connection); } else { _adapter.Execute(commandBuilder, _transaction); } return resultRequired ? finder.FindOne(tableName, criteria) : null; } var inserter = _transaction == null ? new AdoAdapterInserter(_adapter, connection) : new AdoAdapterInserter(_adapter, _transaction); return inserter.Insert(tableName, data, resultRequired); }
public IDictionary<string, string> Reassemble(string clientId, IDictionary<string, string> input) { var expectedDatabusProperties = input.Where(kv => kv.Key.Contains(HeaderMapper.DATABUS_PREFIX)).ToList(); if (!expectedDatabusProperties.Any()) { return input; } lock (headers) { IDictionary<string, string> collection; if (!headers.TryGetValue(clientId, out collection)) { throw new ChannelException(412, string.Format("Expected {0} databus properties. None were received. Please resubmit.", expectedDatabusProperties.Count)); } foreach (var propertyHeader in expectedDatabusProperties) { if (!collection.ContainsKey(propertyHeader.Key)) { throw new ChannelException(412, string.Format("Databus property {0} was never received. Please resubmit.", propertyHeader.Key)); } input[propertyHeader.Key] = collection[propertyHeader.Key]; } headers.Remove(clientId); } return input; }
/// <summary> /// Gets the type of a Policy resource given its <paramref name="data"/>. /// </summary> /// <param name="data">The resource data.</param> /// <returns>The resource type.</returns> protected override Type GetResolvedTypeInternal(IDictionary <string, object> data) { var value = data ?.Where(kv => kv.Key.Equals("type", StringComparison.OrdinalIgnoreCase)) ?.FirstOrDefault().Value?.ToString(); if (string.IsNullOrEmpty(value)) { return(typeof(Policy)); } if (value.Equals("IDP_DISCOVERY")) { return(typeof(IdentityProviderPolicy)); } if (value.Equals("OAUTH_AUTHORIZATION_POLICY")) { return(typeof(OAuthAuthorizationPolicy)); } if (value.Equals("OKTA_SIGN_ON")) { return(typeof(OktaSignOnPolicy)); } if (value.Equals("PASSWORD")) { return(typeof(PasswordPolicy)); } return(typeof(Policy)); }
/// <summary> /// Сохраняет заголовки входящего сообщения. /// </summary> /// <param name="headers">Заголовки входящего сообщения.</param> public void Store(IDictionary<string, object> headers) { var refindedHeaders = headers .Where(p => !this.blackHeaderSet.Contains(p.Key)) .ToDictionary(p => p.Key, p => p.Value); CallContext.LogicalSetData(this.storageKey, refindedHeaders); }
public void Configure(Action <PolicyConfiguration> configuration) { var impl = new PolicyConfigurationImpl(); configuration(impl); _applyTo = impl.WhereToApply; _pattern = impl.Pattern; _priority = impl.Priority; _arguments = impl.Arguments; foreach (var argument in _arguments?.Where(x => x.Value.IsNull()).Select(x => x.Key)) { _errors.Add(new ErrorImpl($"Argument '{argument}' has been set without a corresponding value.")); } if (!_arguments.TryGetValue("ha-mode", out var haMode)) { return; } string mode = haMode.Value.ToString().Trim(); if ((mode.Convert() == HighAvailabilityModes.Exactly || mode.Convert() == HighAvailabilityModes.Nodes) && !_arguments.ContainsKey("ha-params")) { _errors.Add(new ErrorImpl($"Argument 'ha-mode' has been set to {mode}, which means that argument 'ha-params' has to also be set")); } }
public CommandProvider(CommandConfigurer commandConfigurer) { _commands = new Dictionary<string, StackCommand>(); _constants = new Dictionary<String, double>(); commandConfigurer.config(this); _operators = _commands.Where(entry => entry.Value is Operator).Select(entry => entry.Key).ToList(); }
public IDictionary<string, string> Reassemble(string clientId, IDictionary<string, string> input) { var expectedDatabusProperties = input.Where(kv => kv.Key.Contains("NServiceBus.DataBus.")).ToList(); if (!expectedDatabusProperties.Any()) { return input; } lock (headers) { IDictionary<string, string> collection; if (!headers.TryGetValue(clientId, out collection)) { var message = string.Format("Expected {0} databus properties. None were received. Please resubmit.",expectedDatabusProperties.Count); throw new ChannelException(412,message); } foreach (var propertyHeader in expectedDatabusProperties) { string propertyValue; if (!collection.TryGetValue(propertyHeader.Key, out propertyValue)) { var message = string.Format("Databus property {0} was never received. Please resubmit.",propertyHeader.Key); throw new ChannelException(412,message); } input[propertyHeader.Key] = propertyValue; } headers.Remove(clientId); } return input; }
/// <summary> /// Returns a list of type string representing each number between a given start number an end number, or a particular phrase based on the divisibility of the number value passed. /// /// </summary> /// <param name="start">starting number</param> /// <param name="end">ending number</param> /// <param name="combos">IDictionary of numbers and associated phrases to replace numbers if any give number is divisible by the passed value.</param> /// <returns></returns> public List<string> GetFizzBuzzCustomResults(short start, short end, IDictionary<short,string> combos) { if (end < start) { throw new ApplicationException("end number must be greater than start number"); } var results = new List<string>(); var extraLoop = combos != null; for (var i = start; i <= end; i++) { if (!extraLoop) { results.Add(i.ToString()); continue;} var sb = new StringBuilder(); var i1 = i; foreach (var combo in combos.Where(combo => i1%combo.Key == 0)) { sb.Append(combo.Value); } results.Add(sb.Length > 0 ? sb.ToString() : i.ToString()); } return results; }
void SerializeElements(IDictionary<string, CfgMetadata> meta, object node, StringBuilder builder, int level) { foreach (var pair in meta.Where(kv => kv.Value.ListType != null)) { var items = (IList)meta[pair.Key].Getter(node); if (items == null || items.Count == 0) continue; Indent(builder, level); builder.Append("<"); builder.Append(pair.Key); builder.AppendLine(">"); foreach (var item in items) { var metaData = CfgMetadataCache.GetMetadata(item.GetType()); Indent(builder, level + 1); builder.Append("<add"); SerializeAttributes(metaData, item, builder); if(JustAttributes(metaData, item)) { builder.AppendLine(" />"); } else { builder.AppendLine(">"); SerializeElements(metaData, item, builder, level + 2); Indent(builder, level + 1); builder.AppendLine("</add>"); } } Indent(builder, level); builder.Append("</"); builder.Append(pair.Key); builder.AppendLine(">"); } }
public void ExploreProjects(IDictionary<IProject, FileSystemPath> projects, MetadataLoader loader, IUnitTestElementsObserver observer) { var silverlightProjects = projects.Where(p => p.Key.IsSilverlight()).ToDictionary(p => p.Key, p => p.Value); this.metadataElementsSource.ExploreProjects(silverlightProjects, loader, observer, this.ExploreAssembly); observer.OnCompleted(); }
public IDictionary<string, object> Insert(AdoAdapter adapter, string tableName, IDictionary<string, object> data, IDbTransaction transaction, bool resultRequired = false) { var table = DatabaseSchema.Get(adapter.ConnectionProvider, adapter.ProviderHelper).FindTable(tableName); if (table == null) throw new SimpleDataException(String.Format("Table '{0}' not found", tableName)); var insertData = data.Where(p => table.HasColumn(p.Key) && !table.FindColumn(p.Key).IsIdentity).ToDictionary(); var insertColumns = insertData.Keys.Select(table.FindColumn).ToArray(); var columnsSql = insertColumns.Select(s => s.QuotedName).Aggregate((agg, next) => String.Concat(agg, ",", next)); var valuesSql = insertColumns.Select((val, idx) => ":p" + idx.ToString()).Aggregate((agg, next) => String.Concat(agg, ",", next)); var insertSql = string.Format("INSERT INTO {0} ({1}) VALUES({2}) RETURNING *;", table.QualifiedName, columnsSql, valuesSql); if (transaction != null) { using(var cmd = transaction.Connection.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = insertSql; return ExecuteInsert(cmd, insertColumns, insertData.Values.ToArray()); } } using (var conn = adapter.ConnectionProvider.CreateConnection()) { conn.Open(); using(var cmd = conn.CreateCommand()) { cmd.CommandText = insertSql; return ExecuteInsert(cmd, insertColumns, insertData.Values.ToArray()); } } }
public static string ToDatabase(IDictionary<string, string> value) { return string.Join( ", ", value.Where(it => it.Value != null).Select(it => "\"{0}\"=>\"{1}\"".With( it.Key.Replace("\\", "\\\\").Replace("\"", "\\\""), it.Value.Replace("\\", "\\\\").Replace("\"", "\\\"")))); }
private string GetAttributes(IDictionary<string, object> htmlAttributes, ISet<string> skippedAttributes) { var attributes = String.Join(" ", htmlAttributes .Where(kvp => !skippedAttributes.Contains(kvp.Key)) .Select(kvp => kvp.Key + "=\"" + kvp.Value + "\"")); return attributes != "" ? (" " + attributes) : ""; }
/// <summary> /// Gets the type of a Application resource given its <paramref name="data"/>. /// </summary> /// <param name="data">The resource data.</param> /// <returns>The resource type.</returns> protected override Type GetResolvedTypeInternal(IDictionary <string, object> data) { var value = data ?.Where(kv => kv.Key.Equals("signOnMode", StringComparison.OrdinalIgnoreCase)) ?.FirstOrDefault().Value?.ToString(); if (string.IsNullOrEmpty(value)) { return(typeof(Application)); } if (value.Equals("AUTO_LOGIN")) { return(typeof(AutoLoginApplication)); } if (value.Equals("BASIC_AUTH")) { return(typeof(BasicAuthApplication)); } if (value.Equals("BOOKMARK")) { return(typeof(BookmarkApplication)); } if (value.Equals("BROWSER_PLUGIN")) { return(typeof(BrowserPluginApplication)); } if (value.Equals("OPENID_CONNECT")) { return(typeof(OpenIdConnectApplication)); } if (value.Equals("SAML_1_1")) { return(typeof(SamlApplication)); } if (value.Equals("SAML_2_0")) { return(typeof(SamlApplication)); } if (value.Equals("SECURE_PASSWORD_STORE")) { return(typeof(SecurePasswordStoreApplication)); } if (value.Equals("WS_FEDERATION")) { return(typeof(WsFederationApplication)); } return(typeof(Application)); }
/// <summary> /// Initializes a new instance of the <see cref="Column" /> class. /// </summary> /// <param name="tSqlObject">The TSqlObject representing the column.</param> /// <param name="tSqlTable">The table or view this column belongs to.</param> /// <param name="primaryKeys">The primary keys.</param> /// <param name="foreignKeys">The foreign keys.</param> public Column(dac.TSqlObject tSqlObject, dac.TSqlObject tSqlTable, IEnumerable<dac.TSqlObject> primaryKeys, IDictionary<dac.TSqlObject, IEnumerable<ForeignKeyConstraintDefinition>> foreignKeys) { this.Name = tSqlObject.Name.Parts.Last(); var fullName = string.Join(".", tSqlObject.Name.Parts); this.IsPrimaryKey = primaryKeys.Any(p => string.Join(".", p.Name.Parts) == fullName); // Get relationships where this column is the child. IEnumerable<ForeignKeyConstraintDefinition> myForeignKeys; foreignKeys.TryGetValue(tSqlTable, out myForeignKeys); myForeignKeys = myForeignKeys ?? Enumerable.Empty<ForeignKeyConstraintDefinition>(); this.ParentRelationships = from f in myForeignKeys where f.Columns.Any(c => c.Value == this.Name) select new RelationshipIdentifier { TableOrView = f.ReferenceTableName.BaseIdentifier != null ? f.ReferenceTableName.BaseIdentifier.Value : null, Schema = f.ReferenceTableName.SchemaIdentifier != null ? f.ReferenceTableName.SchemaIdentifier.Value : null, Database = f.ReferenceTableName.DatabaseIdentifier != null ? f.ReferenceTableName.DatabaseIdentifier.Value : null, Columns = f.ReferencedTableColumns.Select(c => c.Value) }; this.IsForeignKey = this.ParentRelationships.Any(); // Get relationships where this column is the parent. var childTables = foreignKeys.Where(f => f.Value.Any(v => v.ReferenceTableName.BaseIdentifier.Value == tSqlTable.Name.Parts.Last() && v.ReferencedTableColumns.Any(c => c.Value == this.Name))); this.ChildRelationships = from t in childTables from r in t.Value let tableParts = t.Key.Name.Parts.Count() select new RelationshipIdentifier { TableOrView = t.Key.Name.Parts.Last(), Schema = tableParts > 1 ? t.Key.Name.Parts.ElementAt(tableParts - 2) : null, Database = tableParts > 2 ? t.Key.Name.Parts.ElementAt(tableParts - 3) : null, Columns = r.Columns.Select(c => c.Value) }; if (tSqlObject.ObjectType.Name == "TableTypeColumn") { var sqlDataTypeName = tSqlObject.GetReferenced(dac.TableTypeColumn.DataType).ToList().First().Name.Parts.Last(); this.DataTypes = DataTypeHelper.Instance.GetMap(TypeFormat.SqlServerDbType, sqlDataTypeName); this.IsIdentity = dac.TableTypeColumn.IsIdentity.GetValue<bool>(tSqlObject); this.IsNullable = dac.TableTypeColumn.Nullable.GetValue<bool>(tSqlObject); this.Precision = dac.TableTypeColumn.Precision.GetValue<int>(tSqlObject); this.Scale = dac.TableTypeColumn.Scale.GetValue<int>(tSqlObject); this.Length = dac.TableTypeColumn.Length.GetValue<int>(tSqlObject); } else { var sqlDataTypeName = tSqlObject.GetReferenced(dac.Column.DataType).ToList().First().Name.Parts.Last(); this.DataTypes = DataTypeHelper.Instance.GetMap(TypeFormat.SqlServerDbType, sqlDataTypeName); this.IsIdentity = dac.Column.IsIdentity.GetValue<bool>(tSqlObject); this.IsNullable = dac.Column.Nullable.GetValue<bool>(tSqlObject); this.Precision = dac.Column.Precision.GetValue<int>(tSqlObject); this.Scale = dac.Column.Scale.GetValue<int>(tSqlObject); this.Length = dac.Column.Length.GetValue<int>(tSqlObject); } }
/// <summary> /// Gets the type of a Factor resource given its <paramref name="data"/>. /// </summary> /// <param name="data">The resource data.</param> /// <returns>The resource type.</returns> protected override Type GetResolvedTypeInternal(IDictionary <string, object> data) { var value = data ?.Where(kv => kv.Key.Equals("factorType", StringComparison.OrdinalIgnoreCase)) ?.FirstOrDefault().Value?.ToString(); if (string.IsNullOrEmpty(value)) { return(typeof(Factor)); } if (value.Equals("call")) { return(typeof(CallFactor)); } if (value.Equals("email")) { return(typeof(EmailFactor)); } if (value.Equals("push")) { return(typeof(PushFactor)); } if (value.Equals("question")) { return(typeof(SecurityQuestionFactor)); } if (value.Equals("sms")) { return(typeof(SmsFactor)); } if (value.Equals("token")) { return(typeof(TokenFactor)); } if (value.Equals("token:hardware")) { return(typeof(HardwareFactor)); } if (value.Equals("token:software:totp")) { return(typeof(TotpFactor)); } if (value.Equals("web")) { return(typeof(WebFactor)); } return(typeof(Factor)); }
public static void Automate(PublisherSettings settings, PublishingRecord record, IDictionary<string, bool> attachments, string spaceId) { try { // Launch a FireFox instance var driver = new FirefoxDriver(); // How long WebDriver will wait for an element to exist in the DOM before timeout driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 20)); // Go to login page, fill in credentials and click Login driver.Navigate().GoToUrl(string.Format("{0}/login", settings.Url)); driver.FindElement(By.Name("user[login]")).SendKeys(settings.UserName); driver.FindElement(By.Name("user[password]")).SendKeys(settings.Password); driver.FindElement(By.Name("commit")).Click(); // Go to ticket page, fill in summary and description driver.Navigate().GoToUrl(string.Format("{0}/spaces/{1}/tickets/new", settings.Url, spaceId)); driver.FindElement(By.Name("ticket[summary]")).SendKeys(record.Title); // append link-only attachment to defect summary string summary = record.Summary + ToEmbeddedLinks(attachments.Where(x => x.Value).Select(x => x.Key).ToArray()); driver.FindElement(By.Name("ticket[description]")).SendKeys(ReplaceMarkers(record.Summary)); // Add attachments int i = 0; foreach (var attachment in attachments.Where(x => !x.Value)) { // Click the "Add attachments" link driver.FindElement(By.ClassName("item-attachment")).Click(); // Fill file path to the file upload control driver.FindElement(By.Name(string.Format("ticket[new_attachment_attributes][{0}][file]", ++i))) .SendKeys(attachment.Key); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Represents menu item. /// </summary> /// <param name="title">Menu item title.</param> /// <param name="description">Menu item description.</param> /// <param name="actions">Menu item actions map.</param> public MenuItem(string title, IDictionary <ConsoleKey, MenuAction> actions) { Title = title; _actions = actions? .Where(a => a.Value != null) .ToDictionary(a => a.Key, a => a.Value) ?? new Dictionary <ConsoleKey, MenuAction>(); }
public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs) { string propertyName = null; string propertyTextValue = null; PropertySerializerEntry propertySerializerEntry = null; try { if (instance == null) instance = type.CreateInstance(); foreach (var pair in keyValuePairs.Where(x => !string.IsNullOrEmpty(x.Value))) { propertyName = pair.Key; propertyTextValue = pair.Value; if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry)) { if (propertyName != "format" && propertyName != "callback" && propertyName != "debug") { Log.WarnFormat("Property '{0}' does not exist on type '{1}'", propertyName, type.FullName); } continue; } if (propertySerializerEntry.PropertySetFn == null) { Log.WarnFormat("Could not set value of read-only property '{0}' on type '{1}'", propertyName, type.FullName); continue; } var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue); if (value == null) { Log.WarnFormat("Could not create instance on '{0}' for property '{1}' with text value '{2}'", instance, propertyName, propertyTextValue); continue; } propertySerializerEntry.PropertySetFn(instance, value); } return instance; } catch (Exception ex) { var serializationException = new SerializationException("KeyValueDataContractDeserializer: Error converting to type: " + ex.Message, ex); if (propertyName != null) { serializationException.Data.Add("propertyName", propertyName); } if (propertyTextValue != null) { serializationException.Data.Add("propertyValueString", propertyTextValue); } if (propertySerializerEntry != null && propertySerializerEntry.PropertyType != null) { serializationException.Data.Add("propertyType", propertySerializerEntry.PropertyType); } throw serializationException; } }
private object GetEntity(EntityAction action, IDictionary<string, object> parameters) { var repositoryType = typeof (IDynamicRepository<>).MakeGenericType(action.Type); var getCommand = repositoryType.GetMethod("Get"); var repository = _Locator.GetInstance(repositoryType); // Todo this seems to bypass our security checks for this method... possibly we should have a thing to check this one too. Not sure how, maybe checking access should be a reusable service instead of a pipeline component. // I would really like to have a stage to do this repository to entity fetching, maybe a DomainRepositoryActionInvoker stage? return getCommand.Invoke(repository, parameters.Where(p => p.Key.ToLowerInvariant() == "id").Select(p => p.Value).ToArray()); }
/// <summary>Creates a new resolver, adds the given schema definitions and registers an exception schema if available.</summary> /// <param name="settings">The settings.</param> /// <param name="definitions">The definitions.</param> public static SwaggerToCSharpTypeResolver CreateWithDefinitions(CSharpGeneratorSettings settings, IDictionary<string, JsonSchema4> definitions) { var exceptionSchema = definitions.ContainsKey("Exception") ? definitions["Exception"] : null; var resolver = new SwaggerToCSharpTypeResolver(settings, exceptionSchema); resolver.AddGenerators(definitions .Where(p => p.Value != exceptionSchema) .ToDictionary(p => p.Key, p => p.Value)); return resolver; }
static bool JustAttributes(IDictionary<string, CfgMetadata> meta, object node) { if(meta.All(kv => kv.Value.ListType == null)) return true; foreach(var pair in meta.Where(kv=>kv.Value.ListType != null)){ var list = (IList)meta[pair.Key].Getter(node); if (list != null && list.Count > 0) return false; } return true; }
public string GetResponse(string host, IDictionary<string, object> arguments, bool useCookies = false) { const string contentType = "application/x-www-form-urlencoded"; const string requestType = "POST"; Logging.LogLine("POSTing to " + host + " " + arguments.GetHashCode(), "browser serv"); var isFirst = true; if (useCookies) { if (!arguments.ContainsKey("csrf_token")) arguments["csrf_token"] = GetCsrfToken(); } var totalRequest = new StringBuilder(); foreach (var arg in arguments.Where(arg => arg.Key != "type")) { if (!isFirst) totalRequest.Append('&'); else isFirst = false; totalRequest.Append(arg.Key); totalRequest.Append('='); totalRequest.Append(HttpUtility.UrlEncode((string) arg.Value)); } var toPost = Encoding.ASCII.GetBytes(totalRequest.ToString()); var cachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); var req = (HttpWebRequest) WebRequest.Create(host); req.CachePolicy = cachePolicy; req.Method = requestType; req.ContentType = contentType; req.ContentLength = toPost.Length; req.UserAgent = Constants.FriendlyName; if (useCookies) req.CookieContainer = loginCookies; using (var postStream = req.GetRequestStream()) postStream.Write(toPost, 0, toPost.Length); using (var rep = (HttpWebResponse) req.GetResponse()) using (var answerStream = rep.GetResponseStream()) { if (answerStream == null) return null; using (var answerReader = new StreamReader(answerStream)) return answerReader.ReadToEnd(); } }
public Document(DocumentTable table, string document, IDictionary<string, object> projections) { Table = table; DocumentAsString = document; idColumn = projections.Single(x => x.Key == table.IdColumn.Name); documentColumn = projections.Single(x => x.Key == table.DocumentColumn.Name); etagColumn = projections.Single(x => x.Key == table.EtagColumn.Name); this.projections = projections.Where(x => !(x.Key is SystemColumn)) .Select(x => new Projection(x.Key, x.Value)) .ToList(); }
private static void RemoveOptionalRoutingParameters(IDictionary<string, object> routeValues) { var optionalParams = routeValues .Where(x => x.Value == RouteParameter.Optional) .Select(x => x.Key) .ToList(); foreach (var key in optionalParams) { routeValues.Remove(key); } }
/// <summary> /// 摘要: /// 清理参数集, 为签名做准备. /// /// 备注: /// 返回新的字典实例, 包含清理过的参数集. /// /// 清理的时候会: /// 1. 移除值为null或者String.Empty的参数 /// 2. 移除键为"sign"或者"sign_type"的参数. /// </summary> /// <param name="input">参数集</param> /// <returns>新的字典, 包含清理过的参数集</returns> public static Dictionary<string, string> GetClearedParametersForSign(IDictionary<string, string> input) { ThrowHelper.ThrowNullArgument(input, nameof(input)); var q = input.Where(pair => !pair.Key.Equals("sign", StringComparison.CurrentCultureIgnoreCase) && !string.IsNullOrEmpty(pair.Value) ); return q.ToDictionary(pair => pair.Key, pair => pair.Value); }
private static Dictionary<Column, object> BuildDataDictionary(AdoAdapter adapter, IDictionary<string, object> data, Table table) { Func<string, bool> columnFilter = key => table.HasColumn(key) && (table.FindColumn(key).IsWriteable || ((adapter.AdoOptions != null && adapter.AdoOptions.IdentityInsert) && table.FindColumn(key).IsIdentity)); return data.Where(kvp => columnFilter(kvp.Key)) .ToDictionary(kvp => table.FindColumn(kvp.Key), kvp => kvp.Value); }
public override void Configure(IDictionary<string, string> properties) { try { string hostname = Dns.GetHostName().ToLowerInvariant(); string bindPrefix = properties.ContainsKey("bind") ? properties["bind"] : DEFAULT_BIND_URL; bindUri = new System.Uri(bindPrefix.Replace("*", hostname)); XmppRuntimeInfo.BoshUri = bindUri; string policyPrefix = properties.ContainsKey("policy") ? properties["policy"] : bindUri.Scheme + "://*:" + bindUri.Port; domainUri = new System.Uri(policyPrefix.Replace("*", hostname)); string apiPrefix = properties.ContainsKey("api") ? properties["api"] : null; apiUri = apiPrefix != null ? new System.Uri(apiPrefix.Replace("*", hostname)) : null; if (policyPrefix.Contains(".")) policyPrefix = policyPrefix.Substring(0, policyPrefix.LastIndexOf("/")); if (!policyPrefix.EndsWith("/")) policyPrefix += "/"; if (apiPrefix != null && !apiPrefix.EndsWith("/")) apiPrefix += "/"; httpListener.Prefixes.Add(bindPrefix); httpListener.Prefixes.Add(policyPrefix); if (apiPrefix != null) httpListener.Prefixes.Add(apiPrefix); log.InfoFormat("Configure listener {0} on {1}", Name, bindPrefix); log.InfoFormat("Configure policy {0} on {1}", Name, policyPrefix); if (apiPrefix != null) log.InfoFormat("Configure api {0} on {1}", Name, apiPrefix); BoshXmppHelper.CompressResponse = properties.ContainsKey("compress") ? bool.Parse(properties["compress"]) : true; if (properties.ContainsKey("policyFile")) policyFile = properties["policyFile"]; policyFile = PathUtils.GetAbsolutePath(policyFile); if (properties.ContainsKey("maxpacket")) { var value = 0L; if (long.TryParse(properties["maxpacket"], out value)) maxPacket = value; } foreach (var responderType in properties.Where(property => property.Key.StartsWith("responder")).Select(property => Type.GetType(property.Value)).Where(responderType => responderType != null)) { if (responderType.GetInterfaces().Contains(typeof(IHttpResponder))) { httpResponders.Add((IHttpResponder)Activator.CreateInstance(responderType)); } } } catch (Exception e) { log.DebugFormat("Error configure listener {0}: {1}", Name, e); throw; } }
/// <summary> /// Constructor for ODataQueryOptionParser /// </summary> /// <param name="model">Model to use for metadata binding.</param> /// <param name="targetEdmType">The target EdmType to apply the query option on.</param> /// <param name="targetNavigationSource">The target navigation source to apply the query option on.</param> /// <param name="queryOptions">The dictionary storing query option key-value pairs.</param> public ODataQueryOptionParser(IEdmModel model, IEdmType targetEdmType, IEdmNavigationSource targetNavigationSource, IDictionary<string, string> queryOptions) { ExceptionUtils.CheckArgumentNotNull(queryOptions, "queryOptions"); this.targetEdmType = targetEdmType; this.targetNavigationSource = targetNavigationSource; this.queryOptions = queryOptions; this.Configuration = new ODataUriParserConfiguration(model) { ParameterAliasValueAccessor = new ParameterAliasValueAccessor(queryOptions.Where(_ => _.Key.StartsWith("@", StringComparison.Ordinal)).ToDictionary(_ => _.Key, _ => _.Value)) }; }
public PartialAction(string friendlyName, IDictionary<string, string> parameters) : base(friendlyName) { SetInternalValue(KeyPrefix, "action", parameters["action"]); SetInternalValue(KeyPrefix, "controller", parameters["controller"]); SetInternalValue(KeyPrefix, "area", parameters["area"]); var q = parameters .Where(x => !_keys.Contains(x.Key)) .ToDictionary(x => string.Format("{0}{1}", KeyPrefix, x.Key), x => x.Value as object); Parameters.AppendAndUpdate(q); }
private MediaTypeHeaderValue ParseContentTypeHeader(IDictionary <string, string> headers) { string contentType = headers? .Where(hdr => hdr.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)) .Select(hdr => hdr.Value) .FirstOrDefault(); MediaTypeHeaderValue contentTypeHeader = (contentType == null) ? new MediaTypeHeaderValue("text/plain") : MediaTypeHeaderValue.Parse(contentType); contentTypeHeader.CharSet = contentTypeHeader.CharSet ?? Encoding.UTF8.WebName; return(contentTypeHeader); }
public void Validate() { foreach (var argument in _arguments?.Where(x => x.Value.IsNull()).Select(x => x.Key)) { _errors.Add(new(){ Reason = $"Argument '{argument}' has been set without a corresponding value." }); } if (!_arguments.TryGetValue("ha-mode", out var haMode)) { return; } string mode = haMode.Value.ToString().Trim(); if ((mode.Convert() == HighAvailabilityModes.Exactly || mode.Convert() == HighAvailabilityModes.Nodes) && !_arguments.ContainsKey("ha-params")) { _errors.Add(new(){ Reason = $"Argument 'ha-mode' has been set to {mode}, which means that argument 'ha-params' has to also be set" }); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var items = _classValues?.Where(e => e.Value).Select(e => e.Key).ToList(); if (items == null) { base.Process(context, output); return; } if (!string.IsNullOrEmpty(CssClass)) { items.Insert(0, CssClass); } if (items.Any()) { var classes = string.Join(" ", items.ToArray()); output.Attributes.Add("class", classes); } }
/// <summary> /// Gets the type of a BrowserPluginApplication resource given its <paramref name="data"/>. /// </summary> /// <param name="data">The resource data.</param> /// <returns>The resource type.</returns> protected override Type GetResolvedTypeInternal(IDictionary <string, object> data) { var value = data ?.Where(kv => kv.Key.Equals("name", StringComparison.OrdinalIgnoreCase)) ?.FirstOrDefault().Value?.ToString(); if (string.IsNullOrEmpty(value)) { return(typeof(BrowserPluginApplication)); } if (value.Equals("template_swa")) { return(typeof(SwaApplication)); } if (value.Equals("template_swa3field")) { return(typeof(SwaThreeFieldApplication)); } return(typeof(BrowserPluginApplication)); }
/// <summary> /// Gets the type of a PolicyRule resource given its <paramref name="data"/>. /// </summary> /// <param name="data">The resource data.</param> /// <returns>The resource type.</returns> protected override Type GetResolvedTypeInternal(IDictionary <string, object> data) { var value = data ?.Where(kv => kv.Key.Equals("type", StringComparison.OrdinalIgnoreCase)) ?.FirstOrDefault().Value?.ToString(); if (string.IsNullOrEmpty(value)) { return(typeof(PolicyRule)); } if (value.Equals("PASSWORD")) { return(typeof(PasswordPolicyRule)); } if (value.Equals("SIGN_ON")) { return(typeof(OktaSignOnPolicyRule)); } return(typeof(PolicyRule)); }
private IList <AgentService> GetServices(IDictionary <string, AgentService> allServices, string name) => allServices?.Where(s => s.Value.Service.Equals(name, StringComparison.InvariantCultureIgnoreCase)) .Select(x => x.Value).ToList() ?? new List <AgentService>();
private IList <AgentService> GetRequestedServiceInstances(IDictionary <string, AgentService> allServices, string name) { var relatedServices = allServices?.Where(x => x.Value.Service.Equals(name, StringComparison.InvariantCultureIgnoreCase)); return(relatedServices?.Select(x => x.Value).ToList() ?? new List <AgentService>()); }
/// <summary> /// Creates a new BiS solver model. /// </summary> /// <param name="weights">Stat weights. The higher the weight, the more a stat is desirable</param> /// <param name="statReqs">Minimum amount of stats that must be present in a solution</param> /// <param name="baseStats">Stats of a character without any gear</param> /// <param name="gearChoices">Gear items to choose from. Keep this small.</param> /// <param name="foodChoices">List of food choices. This can be fairly large, it doesn't add much complexity.</param> /// <param name="materiaChoices"> /// Dictionary of materia choices; set value to true if the materia is allowed for advanced /// melding. The materia with the highest eligible stat value is chosen. (Note that Tier is 0-indexed) /// </param> /// <param name="relicCaps">Designates customizable relics. Value of an entry determines the total stat cap.</param> /// <param name="overmeldThreshold"> /// Extend the overmelding threshold --- i.e. if you set overmeldThreshold to n, materia /// from materiaChoices that isn't normally allowed in advanced melds can be used up to n times in advanced meld /// </param> /// <param name="allocStatCap">Cap for allocatable stats. Default is 35</param> /// <param name="maximizeUnweightedValues">Maximize unweighted values with a small weight (1e-5)</param> //TODO: this is getting out of hand. need config object asap. //TODO: make model parts pluggable if possible public BisModel(IDictionary <BaseParam, double> weights, IDictionary <BaseParam, int> statReqs, IDictionary <BaseParam, int> baseStats, IEnumerable <Equipment> gearChoices, IEnumerable <FoodItem> foodChoices, IDictionary <MateriaItem, bool> materiaChoices, IDictionary <Equipment, int> relicCaps = null, int overmeldThreshold = 0, int allocStatCap = 35, bool maximizeUnweightedValues = true) { Model = new Model(); StatRequirements = statReqs; Weights = weights; GearChoices = gearChoices.ToList(); FoodChoices = foodChoices.ToList(); RelicCaps = relicCaps; OvermeldThreshold = overmeldThreshold; MaximizeUnweightedValues = maximizeUnweightedValues; // collect stats we care about RelevantStats = Weights.Keys.Union(StatRequirements.Keys).ToList(); // we don't care about materia which affect unneeded stats MateriaChoices = materiaChoices.Where(m => RelevantStats.Contains(m.Key.BaseParam)) .ToDictionary(k => k.Key, k => k.Value); var allEquipSlots = GearChoices.SelectMany(g => g.EquipSlotCategory.PossibleSlots).ToList(); gear = new VariableCollection <EquipSlot, Equipment>(Model, allEquipSlots, GearChoices, type: VariableType.Binary); food = new VariableCollection <FoodItem>(Model, FoodChoices, type: VariableType.Binary); foodcap = new VariableCollection <FoodItem, BaseParam>(Model, FoodChoices, RelevantStats, type: VariableType.Integer, lowerBoundGenerator: (x, b) => 0); materia = new VariableCollection <EquipSlot, Equipment, MateriaItem>(Model, allEquipSlots, GearChoices, MateriaChoices.Keys, type: VariableType.Integer, lowerBoundGenerator: (s, e, bp) => 0); cap = new VariableCollection <EquipSlot, Equipment, BaseParam>(Model, allEquipSlots, GearChoices, RelevantStats, type: VariableType.Integer, lowerBoundGenerator: (s, e, b) => 0); stat = new VariableCollection <BaseParam>(Model, RelevantStats, type: VariableType.Integer, lowerBoundGenerator: x => 0); modstat = new VariableCollection <BaseParam>(Model, RelevantStats, type: VariableType.Integer, lowerBoundGenerator: x => 0); allocstat = new VariableCollection <BaseParam>(Model, RelevantStats, type: VariableType.Integer, lowerBoundGenerator: x => 0); Model.AddConstraint( Expression.Sum(RelevantStats.Where(bp => MainStats.Contains(bp.Name)).Select(bp => allocstat[bp])) <= allocStatCap, "cap allocatable stats"); StatExprs = RelevantStats.ToDictionary(bp => bp, bp => Expression.EmptyExpression); FoodExprs = RelevantStats.ToDictionary(bp => bp, bp => (Expression)stat[bp]); baseStats.ForEach(kv => StatExprs[kv.Key] = kv.Value + Expression.EmptyExpression); var bigM = 50 * GearChoices.Select( g => g.AllParameters.Select( p => p.Values.OfType <ParameterValueFixed>().Select(v => v.Amount).Max()) .Max()).Max(); CreateGearModel(); CreateFoodModel(); CreateObjective(); }
/// <summary> /// Tries to extract an embedded cover from the matroska file. It checks attachments for a matching filename (cover.jpg/png). /// <para> /// <seealso cref="http://www.matroska.org/technical/cover_art/index.html"/>: /// The way to differentiate between all these versions is by the filename. The default filename is cover.(png/jpg) for backward compatibility reasons. /// That is the "big" version of the file (600) in square or portrait mode. It should also be the first file in the attachments. /// The smaller resolution should be prefixed with "small_", ie small_cover.(jpg/png). The landscape variant should be suffixed with "_land", ie cover_land.jpg. /// The filenames are case sensitive and should all be lower case. /// In the end a file could contain these 4 basic cover art files: /// cover.jpg (portrait/square 600) /// small_cover.png (portrait/square 120) /// cover_land.png (landscape 600) /// small_cover_land.jpg (landscape 120) /// </para> /// </summary> /// <returns>Returns the binary data if successful, else <c>null</c></returns> public Task <byte[]> GetCoverAsync() { return(Task.FromResult(_attachments?.Where(a => a.Key.StartsWith("cover.", StringComparison.InvariantCultureIgnoreCase)).Select(a => a.Value).FirstOrDefault())); }
public void Should_be_created_with_all_reference_definitions_containing_a_link_property() { AssertHelper.All( _actualDefinitions.Where(d => d.Key.EndsWith("Reference")).Select( x => (Action) (() => Assert.That(x.Value.properties.Keys, Has.Member("link")))).ToArray()); }
private bool IsSimilar <TKey>(IDictionary <TKey, double> dictionary1, IDictionary <TKey, double> dictionary2) { if (!dictionary1.Any() && !dictionary2.Any()) { return(true); } if (!dictionary1.Any() || !dictionary2.Any()) { return(false); } var similies = dictionary1.Join(dictionary2, c1 => c1.Key, c2 => c2.Key, (c1, c2) => Math.Abs(c1.Value - c2.Value)).Count(x => x < this.optimizerConfig.MaxScoreAdjustment); var disSimilies = dictionary1.Where(x => !dictionary2.ContainsKey(x.Key)).Concat(dictionary2.Where(x => !dictionary1.ContainsKey(x.Key))).Count(); return(similies >= disSimilies * 0.9); }
public virtual ValueId Find(string token) { return(dictionary.Where(pair => token.Equals(pair.Key.Momentless.Token)).Select(pair => pair.Value).FirstOrDefault()); }
/// <summary> /// Populates the given instance's properties where the IDictionary key property names /// match the type's property names case insensitively. /// Population of complex nested child properties is supported by underscoring "_" into the /// nested child properties in the property name. /// </summary> /// <param name="dictionary">Dictionary of property names and values</param> /// <param name="instance">Instance to populate</param> /// <param name="parentInstance">Optional parent instance of the instance being populated</param> /// <returns>Populated instance</returns> public static object Map(IDictionary <string, object> dictionary, object instance, object parentInstance = null) { var fieldsAndProperties = GetFieldsAndProperties(instance.GetType()); foreach (var fieldOrProperty in fieldsAndProperties) { var memberName = fieldOrProperty.Key.ToLower(); var member = fieldOrProperty.Value; // Handle populating simple members on the current type if (dictionary.TryGetValue(memberName, out var value)) { SetMemberValue(member, instance, value); } else { var memberType = GetMemberType(member); // Handle populating complex members on the current type if (memberType.IsClass || memberType.IsInterface) { // Try to find any keys that start with the current member name var nestedDictionary = dictionary.Where(x => x.Key.ToLower().StartsWith(memberName + "_")).ToList(); // If there weren't any keys if (!nestedDictionary.Any()) { // And the parent instance was not null if (parentInstance != null) { // And the parent instance is of the same type as the current member if (parentInstance.GetType() == memberType) { // Then this must be a 'parent' to the current type SetMemberValue(member, instance, parentInstance); } } continue; } var newDictionary = nestedDictionary.ToDictionary( pair => pair.Key.ToLower().Substring(memberName.Length + 1, pair.Key.Length - memberName.Length - 1), pair => pair.Value, StringComparer.OrdinalIgnoreCase); // Try to get the value of the complex member. If the member // hasn't been initialized, then this will return null. var nestedInstance = GetMemberValue(member, instance); // If the member is null and is a class, try to create an instance of the type if (nestedInstance == null && memberType.IsClass) { nestedInstance = memberType.IsArray ? new ArrayList().ToArray(memberType.GetElementType()) : CreateInstance(memberType); } var genericCollectionType = typeof(IEnumerable <>); if (memberType.IsGenericType && genericCollectionType.IsAssignableFrom(memberType.GetGenericTypeDefinition()) || memberType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == genericCollectionType)) { var innerType = memberType.GetGenericArguments().FirstOrDefault(); if (innerType == null) { innerType = memberType.GetElementType(); } nestedInstance = MapCollection(innerType, newDictionary, nestedInstance, instance); } else { nestedInstance = Map(newDictionary, nestedInstance, instance); } SetMemberValue(member, instance, nestedInstance); } } } return(instance); }
public async Task <IHttpActionResult> GetSubmitEvent(string projectId = null, int version = 2, string type = null, [UserAgent] string userAgent = null, [QueryStringParameters] IDictionary <string, string[]> parameters = null) { if (parameters == null || parameters.Count == 0) { return(StatusCode(HttpStatusCode.OK)); } if (projectId == null) { projectId = Request.GetDefaultProjectId(); } // must have a project id if (String.IsNullOrEmpty(projectId)) { return(BadRequest("No project id specified and no default project was found.")); } var project = await GetProjectAsync(projectId); if (project == null) { return(NotFound()); } // TODO: We could save some overhead if we set the project in the overage handler... // Set the project for the configuration response filter. Request.SetProject(project); string contentEncoding = Request.Content.Headers.ContentEncoding.ToString(); var ev = new Event { Type = !String.IsNullOrEmpty(type) ? type : Event.KnownTypes.Log }; string identity = null; string identityName = null; var exclusions = project.Configuration.Settings.GetStringCollection(SettingsDictionary.KnownKeys.DataExclusions).ToList(); foreach (var kvp in parameters.Where(p => !String.IsNullOrEmpty(p.Key) && !p.Value.All(String.IsNullOrEmpty))) { switch (kvp.Key.ToLower()) { case "type": ev.Type = kvp.Value.FirstOrDefault(); break; case "source": ev.Source = kvp.Value.FirstOrDefault(); break; case "message": ev.Message = kvp.Value.FirstOrDefault(); break; case "reference": ev.ReferenceId = kvp.Value.FirstOrDefault(); break; case "date": DateTimeOffset dtValue; if (DateTimeOffset.TryParse(kvp.Value.FirstOrDefault(), out dtValue)) { ev.Date = dtValue; } break; case "value": decimal decValue; if (Decimal.TryParse(kvp.Value.FirstOrDefault(), out decValue)) { ev.Value = decValue; } break; case "geo": GeoResult geo; if (GeoResult.TryParse(kvp.Value.FirstOrDefault(), out geo)) { ev.Geo = geo.ToString(); } break; case "tags": ev.Tags.AddRange(kvp.Value.SelectMany(t => t.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)).Distinct()); break; case "identity": identity = kvp.Value.FirstOrDefault(); break; case "identity.name": identityName = kvp.Value.FirstOrDefault(); break; default: if (kvp.Key.AnyWildcardMatches(exclusions, true)) { continue; } if (kvp.Value.Length > 1) { ev.Data[kvp.Key] = kvp.Value; } else { ev.Data[kvp.Key] = kvp.Value.FirstOrDefault(); } break; } } ev.SetUserIdentity(identity, identityName); try { await _eventPostQueue.EnqueueAsync(new EventPostInfo { MediaType = Request.Content.Headers.ContentType?.MediaType, CharSet = Request.Content.Headers.ContentType?.CharSet, ProjectId = projectId, UserAgent = userAgent, ApiVersion = version, Data = Encoding.UTF8.GetBytes(ev.ToJson(Formatting.None, _jsonSerializerSettings)), ContentEncoding = contentEncoding, IpAddress = Request.GetClientIpAddress() }, _storage); } catch (Exception ex) { _logger.Error().Exception(ex) .Message("Error enqueuing event post.") .Project(projectId) .Identity(ExceptionlessUser?.EmailAddress) .Property("User", ExceptionlessUser) .SetActionContext(ActionContext) .WriteIf(projectId != Settings.Current.InternalProjectId); return(StatusCode(HttpStatusCode.InternalServerError)); } return(StatusCode(HttpStatusCode.OK)); }
public static void LogWriteGenerateResults(IDictionary <Type, GenerationOutput> outputs) { var projects = outputs.Where(o => typeof(Project).IsAssignableFrom(o.Key)); var solutions = outputs.Where(o => typeof(Solution).IsAssignableFrom(o.Key)); var others = outputs.Where(o => ((!typeof(Project).IsAssignableFrom(o.Key)) && (!typeof(Solution).IsAssignableFrom(o.Key)))); var generatedProjectFiles = new List <string>(projects.SelectMany(o => o.Value.Generated)); var skippedProjectFiles = new List <string>(projects.SelectMany(o => o.Value.Skipped)); var generatedSolutionFiles = new List <string>(solutions.SelectMany(o => o.Value.Generated)); var skippedSolutionFiles = new List <string>(solutions.SelectMany(o => o.Value.Skipped)); var generatedOtherFiles = new List <string>(others.SelectMany(o => o.Value.Generated)); var skippedOtherFiles = new List <string>(others.SelectMany(o => o.Value.Skipped)); if (generatedProjectFiles.Count != 0) { LogWriteLine(" " + generatedProjectFiles.Count + " project" + (generatedProjectFiles.Count > 1 ? "s" : "") + " generated:"); generatedProjectFiles.Sort(); foreach (string file in generatedProjectFiles) { LogWriteLine(" {0}", file); } } if (generatedSolutionFiles.Count != 0) { LogWriteLine(" " + generatedSolutionFiles.Count + " solution" + (generatedSolutionFiles.Count > 1 ? "s" : "") + " generated:"); generatedSolutionFiles.Sort(); foreach (string file in generatedSolutionFiles) { LogWriteLine(" {0}", file); } } if (Project.FastBuildMasterGeneratedFiles.Count > 0) { LogWriteLine(" " + Project.FastBuildMasterGeneratedFiles.Count + " fastbuild master bff generated:"); Project.FastBuildMasterGeneratedFiles.Sort(); foreach (string file in Project.FastBuildMasterGeneratedFiles) { LogWriteLine(" {0}", file); } } if (generatedOtherFiles.Count != 0) { LogWriteLine(" " + generatedOtherFiles.Count + " other file" + (generatedOtherFiles.Count > 1 ? "s" : "") + " generated:"); generatedOtherFiles.Sort(); foreach (string file in generatedOtherFiles) { LogWriteLine(" {0}", file); } } LogWriteLine(" Results:"); if (generatedProjectFiles.Count > 0 || skippedProjectFiles.Count > 0) { LogWriteLine(" projects ({0,5} configurations) {1,5} generated, {2,5} up-to-date", Project.Configuration.Count, generatedProjectFiles.Count, skippedProjectFiles.Count); if (Project.FastBuildGeneratedFileCount > 0 || Project.FastBuildUpToDateFileCount > 0) { LogWriteLine(" fastbuild {0,5} generated, {1,5} up-to-date", Project.FastBuildGeneratedFileCount, Project.FastBuildUpToDateFileCount); } } if (generatedSolutionFiles.Count > 0 || skippedSolutionFiles.Count > 0) { LogWriteLine(" solutions ({0,5} configurations) {1,5} generated, {2,5} up-to-date", Solution.Configuration.Count, generatedSolutionFiles.Count, skippedSolutionFiles.Count); } if (Project.BlobGenerated > 0 || Project.BlobUpdateToDate > 0) { LogWriteLine(" blobs {0,5} generated, {1,5} up-to-date", Project.BlobGenerated, Project.BlobUpdateToDate); } if (generatedOtherFiles.Count > 0 || skippedOtherFiles.Count > 0) { LogWriteLine(" other files {0,5} generated, {1,5} up-to-date", generatedOtherFiles.Count, skippedOtherFiles.Count); } }
/// <summary> /// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="redis"></param> /// <param name="items"></param> /// <param name="validFor"></param> public static void Set <T>(this IDatabase redis, IDictionary <string, T> items, TimeSpan validFor) => items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).ToList().ForEach(kvp => redis.StringSet(kvp.Key, Helper.Serialize(kvp.Value), validFor));
static string _extSerialize(IDictionary <string, Configuration.Assembly> list) => list == null ? null : string.Join(" | ", list?.Where(ext => ext.Value.Priority > 0)?.OrderBy(ext => ext.Value.Priority)?.Select(_ => _.Key));
internal static void Set(this IDatabase redis, IDictionary <string, byte[]> items, TimeSpan validFor) => items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).ToList().ForEach(kvp => redis.StringSet(kvp.Key, kvp.Value, validFor));
/// <summary> /// Creates and returns a deep-copy of the specified object while setting the value of the member specified by each expression to its specified value. /// <para> /// This is useful while setting nested struct values (Struct1.Struct2.Property = value). This also is an implementation for the setter part of a 'Lens' in functional programming. Beware that even if an expression to a read-only property/field was specified, the corresponding value will be changed anyway. Properties that contain logic in their getters/setters without a backing-field will be ignored even if specified in an expression. Null expressions are ignored. /// </para> /// </summary> public static T Copy <T>(this T obj, IDictionary <Expression <Func <T, object> >, object> targetValues) => Copy(obj, null, string.Empty, targetValues?.Where(kvp => kvp.Key != null)?.ToDictionary(kvp => ExpressionPath(kvp.Key), kvp => kvp.Value));
private IEnumerable <Failure> GetNullErrors(IDictionary <string, object> actionArguments) { return(actionArguments .Where(i => i.Value == null) .Select(i => new Failure(i.Key, string.Format("The {0} object is required.", i.Key)))); }
public IEnumerator <KeyValuePair <XName, object> > GetEnumerator() { return(_basis.Where(value => value.Value.IsWriteOnly() == _writeOnly).Select(value => new KeyValuePair <XName, object>(value.Key, value.Value.Value)).GetEnumerator()); }
public static Dictionary <string, string> ParamNotNull(this IDictionary <string, string> param) { return(param.Where(x => ValidateHelper.IsPlumpString(x.Key)) .ToDictionary(x => ConvertHelper.GetString(x.Key), x => ConvertHelper.GetString(x.Value))); }
internal IEnumerable <MissingReference> Compare(IDictionary <string, IEnumerable <string> > nuspecReferences, IEnumerable <string> refFiles) { var missingReferences = new List <MissingReference>(); if (nuspecReferences.Count() != 0) { if (refFiles.Count() != 0) { var filesByTFM = refFiles.Where(t => t.Count(m => m == '/') > 1) .GroupBy(t => NuGetFramework.ParseFolder(t.Split('/')[1]).GetShortFolderName(), t => Path.GetFileName(t)); var keys = GetAllKeys(filesByTFM); var missingSubfolderInFiles = nuspecReferences.Keys.Where(t => !keys.Contains(t) && !NuGetFramework.ParseFolder(t).GetShortFolderName().Equals("unsupported") && !NuGetFramework.ParseFolder(t).GetShortFolderName().Equals("any")); if (missingSubfolderInFiles.Count() != 0) { var subfolder = nuspecReferences.Where(t => missingSubfolderInFiles.Contains(t.Key)); foreach (var item in subfolder) { missingReferences.Add(new MissingReference("ref", item.Key, item.Value.ToArray())); } } foreach (var files in filesByTFM) { if (files.Key == "unsupported") { continue; } string[] missingNuspecReferences; string[] missingFiles; IEnumerable <string> anyReferences = null; if (nuspecReferences.TryGetValue(files.Key, out var currentReferences) || nuspecReferences.TryGetValue("any", out anyReferences)) { if (anyReferences != null && currentReferences == null) { missingNuspecReferences = files.Where(m => !anyReferences.Contains(m)).ToArray(); missingFiles = anyReferences.Where(t => !files.Contains(t)).ToArray(); } else { missingNuspecReferences = files.Where(m => !currentReferences.Contains(m)).ToArray(); missingFiles = currentReferences.Where(t => !files.Contains(t)).ToArray(); } } else { missingNuspecReferences = files.ToArray(); missingFiles = Array.Empty <string>(); } if (missingFiles.Length != 0) { missingReferences.Add(new MissingReference("ref", files.Key, missingFiles)); } if (missingNuspecReferences.Length != 0) { missingReferences.Add(new MissingReference("nuspec", files.Key, missingNuspecReferences)); } } } else { foreach (var item in nuspecReferences) { missingReferences.Add(new MissingReference("ref", item.Key, item.Value.ToArray())); } } } return(missingReferences); }
internal static Task SetAsync(this IDatabase redis, IDictionary <string, byte[]> items, TimeSpan validFor, CancellationToken cancellationToken = default(CancellationToken)) => Task.WhenAll(items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).Select(kvp => redis.StringSetAsync(kvp.Key, kvp.Value, validFor).WithCancellationToken(cancellationToken)) ?? new List <Task <bool> >());
/// <summary> /// Adds an item into cache with a specified key (if the key is already existed, then old cached item will be overriden) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="redis"></param> /// <param name="items"></param> /// <param name="validFor"></param> /// <returns></returns> public static Task SetAsync <T>(this IDatabase redis, IDictionary <string, T> items, TimeSpan validFor, CancellationToken cancellationToken = default) => Task.WhenAll(items?.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Key)).Select(kvp => redis.StringSetAsync(kvp.Key, Helper.Serialize(kvp.Value), validFor).WithCancellationToken(cancellationToken)) ?? new List <Task <bool> >());