protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters) { yield return new CommandFilter("[property_type]=1"); yield return new CommandFilter(string.Format("[cube_name]='{0}'" , filters.Single(f => f.Target == Target.Perspectives).Caption )); yield return new CommandFilter(string.Format("[dimension_unique_name]='[{0}]'" , filters.Single(f => f.Target == Target.Dimensions).Caption )); yield return new CommandFilter(string.Format("[hierarchy_unique_name]='[{0}].[{1}]'" , filters.Single(f => f.Target == Target.Dimensions).Caption , filters.Single(f => f.Target == Target.Hierarchies).Caption )); yield return new CommandFilter(string.Format("[level_unique_name]='[{0}].[{1}].[{2}]'" , filters.Single(f => f.Target == Target.Dimensions).Caption , filters.Single(f => f.Target == Target.Hierarchies).Caption , filters.Single(f => f.Target == Target.Levels).Caption )); var filter = filters.SingleOrDefault(f => f.Target == Target.Properties); if (filter!=null) yield return new CommandFilter(string.Format("[property_caption]='{0}'" , filter.Caption )); }
protected override ModelMetadata CreateMetadata( IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var data = base.CreateMetadata( attributes, containerType, modelAccessor, modelType, propertyName); //Enhance the metadata with custom attributes var display = attributes.SingleOrDefault(a => a is DisplayAttribute); if (display != null) { var displayAttribute = ((DisplayAttribute)display); data.Watermark = displayAttribute.Prompt; data.Description = displayAttribute.Description; } var dropDown = attributes.SingleOrDefault(a => a is DropDownPropertyAttribute); if (dropDown != null) { var drop = ((DropDownPropertyAttribute) dropDown); data.AdditionalValues.Add("DropDownProperty.PropertyName", drop.PropertyName); var property = containerType.GetProperty(drop.PropertyName); if(property!= null) { var attr = property.GetCustomAttributes(typeof(RequeridoAttribute), true); data.IsRequired = attr.Any(); } } var cascadingDropDown = attributes.SingleOrDefault(a => a is CascadingDropDownPropertyAttribute); if (cascadingDropDown != null) { var cascading = (CascadingDropDownPropertyAttribute) cascadingDropDown; data.AdditionalValues.Add("CascadingDropDownProperty.ParentPropertyName", cascading.ParentPropertyName); data.AdditionalValues.Add("CascadingDropDownProperty.ParentPrompt", cascading.ParentPrompt); data.AdditionalValues.Add("CascadingDropDownProperty.ActionName", cascading.ActionName); data.AdditionalValues.Add("CascadingDropDownProperty.ControllerName", cascading.ControllerName); data.AdditionalValues.Add("CascadingDropDownProperty.AreaName", cascading.AreaName); data.AdditionalValues.Add("CascadingDropDownProperty.ParameterName", cascading.ParameterName); } var searchDropDown = attributes.SingleOrDefault(a => a is SearcheableDropDownPropertyAttribute); if (searchDropDown != null) { var search = (SearcheableDropDownPropertyAttribute)searchDropDown; data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.ActionName", search.ActionName); data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.ControllerName", search.ControllerName); data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.Template", search.Template); data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.DisplayProperty", search.DisplayProperty); } return data; }
protected override void DoLast(Hero hero, IEnumerable<GameObject> objects) { var cuttableObject = objects.SingleOrDefault(o => o.Properties.Contains(Property.Cuttable)); var cutter = objects.SingleOrDefault(o => o.Properties.Contains(Property.Cutter)); if (cuttableObject == null || cutter == null) { return; } cuttableObject.RemoveFromContainer(); Map.SetHObjectFromDestination(hero.Position, new Log()); return; }
public InstallerStatus PostParameters(IEnumerable<Parameter> parameters) { var connection = parameters.SingleOrDefault(k => k.Key == "connectionString").Value; var containerName = parameters.SingleOrDefault(k => k.Key == "containerName").Value; var rootUrl = parameters.SingleOrDefault(k => k.Key == "rootUrl").Value; var host = $"{rootUrl}{containerName}/"; if (!TestAzureCredentials(connection, containerName)) { return InstallerStatus.ConnectionError; } if (SaveParametersToXdt(this.fileSystemProvidersConfigInstallXdtPath, parameters)) { if (!ExecuteFileSystemConfigTransform() || !ExecuteWebConfigTransform()) { return InstallerStatus.SaveConfigError; } if (!CheckImageProcessorWebCompatibleVersion(ImageProcessorWebMinRequiredVersion)) { return InstallerStatus.ImageProcessorWebCompatibility; } else { // merge in storage url to ImageProcessor security.config xdt SaveBlobPathToImageProcessorSecurityXdt(ImageProcessorSecurityInstallXdtPath, host); // transform ImageProcessor security.config if (ExecuteImageProcessorSecurityConfigTransform()) { if (!ExecuteImageProcessorWebConfigTransform()) { return InstallerStatus.ImageProcessorWebConfigError; } } else { return InstallerStatus.ImageProcessorWebConfigError; } } return InstallerStatus.Ok; } return InstallerStatus.SaveXdtError; }
private void Init( string httpMethod, Uri url, string applicationPath, IEnumerable<KeyValuePair<string, string[]>> formData, IEnumerable<KeyValuePair<string, string>> cookies, Func<byte[], byte[]> cookieDecryptor) { HttpMethod = httpMethod; Url = url; ApplicationUrl = new Uri(url, applicationPath); Form = new ReadOnlyDictionary<string, string>( (formData ?? Enumerable.Empty<KeyValuePair<string, string[]>>()) .ToDictionary(kv => kv.Key, kv => kv.Value.Single())); QueryString = QueryStringHelper.ParseQueryString(url.Query); var relayState = QueryString["RelayState"].SingleOrDefault(); if (relayState != null) { var cookieName = "Kentor." + relayState; if (cookies.Any(c => c.Key == cookieName)) { var cookieData = cookies.SingleOrDefault(c => c.Key == cookieName).Value; var unescapedBase64Data = cookieData .Replace('_', '/') .Replace('-', '+') .Replace('.', '='); CookieData = Encoding.UTF8.GetString(cookieDecryptor( Convert.FromBase64String(unescapedBase64Data))); } } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "status/{documentId:guid}")] HttpRequest req, [CosmosDB(databaseName: "IntermediaryServiceDb", collectionName: "IntermediaryService", ConnectionStringSetting = "CosmosDBConnection", SqlQuery = "select * from IntermediaryService s where s.id = {documentId}")] IEnumerable <IntermediaryServiceDocument> documents, ILogger log) { try { log.LogInformation($"Function 4 processed a request"); var intermediaryServiceDocument = documents?.SingleOrDefault(); //validate that a document was actually retrieved from CosmosDb if (intermediaryServiceDocument == null) { log.LogWarning(UserFriendlyMessages.DocumentNotFound, req); return(new NotFoundObjectResult(UserFriendlyMessages.DocumentNotFound)); } return(new OkObjectResult(intermediaryServiceDocument)); } catch (Exception ex) //gracefully deal with an unhandled exception { log.LogError(ex, UserFriendlyMessages.UnhandledException); return(new StatusCodeResult(500)); } }
public static JwtSecurityToken CreateToken(IEnumerable<Claim> claims, string secretKey, string audience, string issuer, TimeSpan? lifetime) { if (claims == null) { throw new ArgumentNullException("claims"); } if (lifetime != null && lifetime < TimeSpan.Zero) { string msg = CommonResources.ArgMustBeGreaterThanOrEqualTo.FormatForUser(TimeSpan.Zero); throw new ArgumentOutOfRangeException("lifetime", lifetime, msg); } if (string.IsNullOrEmpty(secretKey)) { throw new ArgumentNullException("secretKey"); } if (claims.SingleOrDefault(c => c.Type == JwtRegisteredClaimNames.Sub) == null) { throw new ArgumentOutOfRangeException("claims", LoginResources.CreateToken_SubjectRequired); } // add the claims passed in Collection<Claim> finalClaims = new Collection<Claim>(); foreach (Claim claim in claims) { finalClaims.Add(claim); } // add our standard claims finalClaims.Add(new Claim("ver", "3")); return CreateTokenFromClaims(finalClaims, secretKey, audience, issuer, lifetime); }
/// <summary> /// This gets the permissions for the currently logged in user (or null if no claim) /// </summary> /// <param name="usersClaims"></param> /// <returns></returns> public static IEnumerable <AEAAPermissions> UserPermissionsFromClaims(this IEnumerable <Claim> usersClaims) { var permissionsClaim = usersClaims?.SingleOrDefault(c => c.Type == PermissionConstants.PackedPermissionClaimType); return(permissionsClaim?.Value.UnpackPermissionsFromString()); }
/// <summary> /// Gets the effective domain name of an OrgUnit, based on it's own CustomUrl or it's ancestry. /// </summary> /// <param name="orgUnitId">The org unit id.</param> /// <param name="associations">The associations.</param> /// <returns></returns> public static string GetDomainName(int orgUnitId, IEnumerable<OrgUnitAssociationDto> associations) { var association = associations.SingleOrDefault(a => a.SecondaryId == orgUnitId); if (association != null) { var url = association.SecondaryCustomUrl; if (string.IsNullOrEmpty(url)) { while (association.HasAscendant) { var ascendant = associations.Single(a => a.SecondaryId == association.PrimaryId); if (!string.IsNullOrEmpty(ascendant.SecondaryCustomUrl)) { url = ascendant.SecondaryCustomUrl; break; } association = ascendant; } } if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) { return new Uri(url).Host; } } return string.Empty; }
protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters) { yield return new CommandFilter(string.Format("[cube_name]='{0}'" , filters.Single(f => f.Target == Target.Perspectives).Caption )); var filter = filters.SingleOrDefault(f => f.Target == Target.Sets); if (filter != null) yield return new CommandFilter(string.Format("[set_caption]='{0}'" , filter.Caption )); var dfFilter = filters.SingleOrDefault(f => f.Target == Target.DisplayFolders); if (dfFilter != null) yield return new DisplayFolder(dfFilter.Caption); }
public Message( Guid id, string name, string description, Color backgroundColor, IEnumerable<IMessagePart> parts, EventHandlerCollection eventHandlerCollection = null) { name.ThrowIfNull("name"); description.ThrowIfNull("description"); parts.ThrowIfNull("parts"); parts = parts.ToArray(); IMessagePart question = parts.SingleOrDefault(arg => arg is MessageMananger); if (question != null && parts.Last() != question) { throw new ArgumentException("When a MessageQuestion is present, it must be the last part.", "parts"); } _id = id; Name = name; Description = description; _backgroundColor = backgroundColor; _parts = parts; _eventHandlerCollection = eventHandlerCollection; }
MapValues( IEnumerable<SpecificationProperty> propertyTuples, IEnumerable<KeyValuePair<string, IEnumerable<string>>> options, Func<IEnumerable<string>, System.Type, bool, Maybe<object>> converter, StringComparer comparer) { var sequencesAndErrors = propertyTuples .Select(pt => options.SingleOrDefault( s => s.Key.MatchName(((OptionSpecification)pt.Specification).ShortName, ((OptionSpecification)pt.Specification).LongName, comparer)) .ToMaybe() .Return(sequence => converter(sequence.Value, pt.Property.PropertyType, pt.Specification.ConversionType.IsScalar()) .Return(converted => Tuple.Create( pt.WithValue(Maybe.Just(converted)), Maybe.Nothing<Error>()), Tuple.Create<SpecificationProperty, Maybe<Error>>( pt, Maybe.Just<Error>(new BadFormatConversionError(NameInfo.FromOptionSpecification((OptionSpecification)pt.Specification))))), Tuple.Create(pt, Maybe.Nothing<Error>())) ); return StatePair.Create( sequencesAndErrors.Select(se => se.Item1), sequencesAndErrors.Select(se => se.Item2).OfType<Just<Error>>().Select(se => se.Value)); }
protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters) { yield return new CommandFilter("left(table_name,1)<>'$'"); var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives); if (filter != null) yield return new CommandFilter(string.Format("[table_schema]='{0}'" , filter.Caption )); filter = filters.SingleOrDefault(f => f.Target == Target.Tables); if (filter != null) yield return new CommandFilter(string.Format("[table_name]='{0}'" , filter.Caption )); }
public virtual void Compare (IEnumerable<XElement> source, IEnumerable<XElement> target) { removed.Clear (); modified.Clear (); foreach (var s in source) { SetContext (s); string sn = s.GetAttribute ("name"); var t = target == null ? null : target.SingleOrDefault (x => x.GetAttribute ("name") == sn); if (t == null) { // not in target, it was removed removed.Add (s); } else { t.Remove (); // possibly modified if (Equals (s, t, modified)) continue; // still in target so will be part of Added Modified (s, t, modified); } } // delayed, that way we show "Modified", "Added" and then "Removed" foreach (var item in removed) { SetContext (item); Removed (item); } // remaining == newly added in target if (target != null) { foreach (var item in target) { SetContext (item); Added (item, false); } } }
///<summary>Reads a SchemaMapping from an XML element.</summary> ///<param name="xml">An XML element created by <see cref="SchemaMapping.ToXml"/>.</param> ///<param name="schemas">The schema mapped by the mapping.</param> public static SchemaMapping FromXml(XElement xml, IEnumerable<TableSchema> schemas) { if (xml == null) throw new ArgumentNullException("xml"); if (schemas == null) throw new ArgumentNullException("schemas"); var schemaName = xml.Attribute("SchemaName").Value; var schema = schemas.SingleOrDefault(ts => ts.Name == schemaName); if (schema == null) throw new ArgumentException("Schema '" + schemaName + "' not found", "schemas"); var retVal = new SchemaMapping(schema, false); retVal.SqlName = xml.Attribute("SqlName").Value; if (xml.Attribute("SqlSchemaName") != null) retVal.SqlSchemaName = xml.Attribute("SqlSchemaName").Value; foreach (var cm in xml.Elements("ColumnMapping")) { retVal.Columns.AddMapping( schema.Columns[cm.Attribute("ColumnName").Value], cm.Attribute("SqlName").Value ); } return retVal; }
public BlogPartHandler(IRepository<BlogPartRecord> repository, IWorkContextAccessor workContextAccessor, IEnumerable<IHomePageProvider> homePageProviders, IBlogPathConstraint blogPathConstraint) { _workContextAccessor = workContextAccessor; _blogPathConstraint = blogPathConstraint; _routableHomePageProvider = homePageProviders.SingleOrDefault(p => p.GetProviderName() == RoutableHomePageProvider.Name); Filters.Add(StorageFilter.For(repository)); Action<PublishContentContext, RoutePart> publishedHandler = (context, route) => { if (route.Is<BlogPart>()) { if (route.ContentItem.Id != 0 && route.PromoteToHomePage) _blogPathConstraint.AddPath(""); } else if (route.ContentItem.Id != 0 && route.PromoteToHomePage) { _blogPathConstraint.RemovePath(""); } }; OnPublished<RoutePart>(publishedHandler); OnUnpublished<RoutePart>(publishedHandler); OnGetDisplayShape<BlogPart>((context, blog) => { context.Shape.Description = blog.Description; context.Shape.PostCount = blog.PostCount; }); }
public static PropertyDescriptor GetReferenceProperty(PropertyDescriptor pd, IEnumerable<PropertyDescriptor> properties) { string refPropertyName = pd.Name + "Reference"; return properties.SingleOrDefault<PropertyDescriptor>(delegate(PropertyDescriptor p) { return (p.Name == refPropertyName); }); }
public static List GetList(IEnumerable<List> listCollection, string listName, bool breakIfNull = true) { var retVal = listCollection.SingleOrDefault(l => l.RootFolder.Name == listName); if (retVal == null && breakIfNull) throw new Exception(String.Format("List {0} not found", listName)); return retVal; }
public static int?UsedWeight(this IEnumerable <Tuple <string, string> > headers) { if (int.TryParse(headers?.SingleOrDefault(s => s.Item1 == "X-MBX-USED-WEIGHT")?.Item2, out var value)) { return(value); } return(null); }
/// <summary> /// Resolves property ignoring casing /// </summary> /// <param name="type"></param> /// <param name="propertyName"></param> /// <returns></returns> internal string ResolveName(IEnumerable<PropertyInfo> properties, string propertyName) { if (properties == null) throw new ArgumentNullException("properties"); var prop = properties.SingleOrDefault(p => p.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)); return prop != null ? prop.Name : propertyName; }
public static Maybe<char> WithSeparator(string name, IEnumerable<OptionSpecification> specifications, StringComparer comparer) { return specifications.SingleOrDefault( a => name.MatchName(a.ShortName, a.LongName, comparer) && a.Separator != '\0') .ToMaybe() .Return(spec => Maybe.Just(spec.Separator), Maybe.Nothing<char>()); }
public void Check(IEnumerable<IComponent> components, IStore<string, IArtificialIntelligence> aiStore) { var groupedByOwener = components.GroupBy(x => x.OwnerId); foreach (var group in groupedByOwener) { var enemies = components.Except(group).OfType<IFieldOfVision>(); foreach (var component in group) { foreach (var enemy in enemies) { var isInFieldOfVision = enemy.IsInFieldOfVision(component.Position); if (isInFieldOfVision) { var artificialIntelligence = aiStore.Get(enemy.OwnerId); artificialIntelligence.Fire(new ComponentSpottedEvent(enemy.OwnerId, enemy.Id, component.Id, component.OwnerId, component.Position.X, component.Position.Y, component.GetType())); SpottedUnitsStore.Store(component.Id, enemy.OwnerId); } } } } //foreach (var group in groupedByOwener) { // var others = components.Except(group).OfType<IFieldOfVision>(); // foreach (var component in group) { // var spottingUnits = others.Where(x => x.IsInFieldOfVision(component.Position)); // foreach (var fieldOfVision in spottingUnits) { // var artificialIntelligence = aiStore.Get(fieldOfVision.OwnerId); // artificialIntelligence.Fire(new ComponentSpottedEvent(fieldOfVision.OwnerId,fieldOfVision.Id,component.Id,component.OwnerId,component.Position.X,component.Position.Y, component.GetType())); // SpottedUnitsStore.Store(component.Id,fieldOfVision.OwnerId); // } // } //} var spottedUnits = SpottedUnitsStore.GetKeys(); Parallel.ForEach(spottedUnits, (suid,loopState) => { var spottedComponent = components.SingleOrDefault(x => x.Id.Equals(suid)); if(spottedComponent == null) { SpottedUnitsStore.Remove(suid); } else { var enemyOwnerId = SpottedUnitsStore.Get(suid); if(enemyOwnerId == null) return; var enemyUnits = components.Where(x => x.OwnerId.Equals(enemyOwnerId)).OfType<IFieldOfVision>(); if(enemyUnits.All(x => !x.IsInFieldOfVision(spottedComponent.Position))) { SpottedUnitsStore.Remove(spottedComponent.Id); var artificialIntelligence = aiStore.Where(x => x.Id.Equals(enemyOwnerId)).First(); artificialIntelligence.Fire(new ComponentLeftFieldOfVisionEvent(artificialIntelligence.Id,spottedComponent.Id,spottedComponent.OwnerId,spottedComponent.Position.X,spottedComponent.Position.Y,spottedComponent.GetType())); } } }); }
public bool Do(Hero hero, IEnumerable<GameObject> objects) { var branch = objects.SingleOrDefault(o => o is Branch); var stone = objects.SingleOrDefault(ao => ao.Properties.Contains(Property.Cutter)); if (branch == null || stone == null) return true; branch.RemoveFromContainer(); var diggingStick = new DiggingStick(); if (!hero.AddToBag(diggingStick)) { Game.Map.SetHObjectFromDestination(hero.Position, diggingStick); } return true; }
private static void AssertMemberType(DataType expectedType, IEnumerable<Binding> memberBindings, string key) { var binding = memberBindings.SingleOrDefault(x => x.Identifier == key); if (binding != null) binding.Type.ShouldEqual(expectedType); else throw new Exception("Failed to look up the type of '" + key + "' in the Scope"); }
protected virtual PropertyInfo GetInterfaceNamedStructureIdProperty(Type structureType, IEnumerable<PropertyInfo> properties) { if (!structureType.IsInterface) return null; var propertyName = StructureIdPropertyNames.GetInterfaceTypeNamePropertyNameFor(structureType); return properties.SingleOrDefault(p => p.Name.Equals(propertyName)); }
public IVirtualMachine Attach(IEnumerable<KeyValuePair<string, IConnectorArgument>> arguments) { var pid = (IConnectorIntegerArgument)arguments.Single(i => i.Key == "pid").Value; var sourcePaths = (IConnectorStringArgument)arguments.SingleOrDefault(i => i.Key == "sourcePaths").Value; VirtualMachine virtualMachine = VirtualMachine.BeginAttachToProcess(pid.Value, sourcePaths.StringValue.Split(';')); virtualMachine.AttachComplete += OnAttachComplete; return virtualMachine; }
internal TableColumns( DBConnection cn, string table, bool forRevisionHistoryLogic ) { try { // NOTE: Cache this result. AllColumns = Column.GetColumnsInQueryResults( cn, "SELECT * FROM " + table, true ); foreach( var col in AllColumns ) { // This hack allows code to be generated against a database that is configured for ASP.NET Application Services. var isAspNetApplicationServicesTable = table.StartsWith( "aspnet_" ); if( !( cn.DatabaseInfo is OracleInfo ) && col.DataTypeName == typeof( string ).ToString() && col.AllowsNull && !isAspNetApplicationServicesTable ) throw new UserCorrectableException( "String column " + col.Name + " allows null, which is not allowed." ); } // Identify key, identity, and non identity columns. var nonIdentityColumns = new List<Column>(); foreach( var col in AllColumns ) { if( col.IsKey ) keyColumns.Add( col ); if( col.IsIdentity ) { if( identityColumn != null ) throw new UserCorrectableException( "Only one identity column per table is supported." ); identityColumn = col; } else nonIdentityColumns.Add( col ); } if( !keyColumns.Any() ) throw new UserCorrectableException( "The table must contain a primary key or other means of uniquely identifying a row." ); // If the table has a composite key, try to use the identity as the key instead since this will enable InsertRow to return a value. if( identityColumn != null && keyColumns.Count > 1 ) { keyColumns.Clear(); keyColumns.Add( identityColumn ); } RowVersionColumn = AllColumns.SingleOrDefault( i => i.IsRowVersion ); AllColumnsExceptRowVersion = AllColumns.Where( i => !i.IsRowVersion ).ToArray(); AllNonIdentityColumnsExceptRowVersion = nonIdentityColumns.Where( i => !i.IsRowVersion ).ToArray(); if( forRevisionHistoryLogic ) { if( keyColumns.Count != 1 ) { throw new UserCorrectableException( "A revision history modification class can only be created for tables with exactly one primary key column, which is assumed to also be a foreign key to the revisions table." ); } primaryKeyAndRevisionIdColumn = keyColumns.Single(); if( primaryKeyAndRevisionIdColumn.IsIdentity ) throw new UserCorrectableException( "The revision ID column of a revision history table must not be an identity." ); } dataColumns = AllColumns.Where( col => !col.IsIdentity && !col.IsRowVersion && col != primaryKeyAndRevisionIdColumn ).ToArray(); } catch( Exception e ) { throw UserCorrectableException.CreateSecondaryException( "An exception occurred while getting columns for table " + table + ".", e ); } }
public bool Do(Hero hero, IEnumerable<GameObject> objects) { var branch = objects.SingleOrDefault(o => o is Branch); var stone = objects.SingleOrDefault(o => o is Rock); if (branch == null || stone == null) return true; branch.RemoveFromContainer(); stone.RemoveFromContainer(); var axe = new StoneAxe(); if (!hero.AddToBag(axe)) { Game.Map.SetHObjectFromDestination(hero.Position, axe); } return true; }
public static void Equal(IEnumerable<IdentityUserLogin> expected, IEnumerable<IdentityUserLogin> actual) { Assert.True((expected == null && actual == null) || (expected != null && actual != null)); Assert.Equal(expected.Count(), actual.Count()); foreach (var e in expected) { Assert.True(actual.SingleOrDefault(a => a.LoginProvider == e.LoginProvider && a.ProviderKey == e.ProviderKey && a.ProviderDisplayName == e.ProviderDisplayName) != null); } }
public static void Equal(IEnumerable<IdentityClaim> expected, IEnumerable<IdentityClaim> actual) { Assert.True((expected == null && actual == null) || (expected != null && actual != null)); Assert.Equal(expected.Count(), actual.Count()); foreach(var e in expected) { Assert.True(actual.SingleOrDefault(a => a.ClaimType == e.ClaimType && a.ClaimValue == e.ClaimValue) != null); } }
private IElement CreateElement(RenderContext renderContext, XmlNode currentNode, IEnumerable<Type> availableTypes) { var nodeName = currentNode.LocalName; Type controlType = availableTypes.SingleOrDefault(a => a.GetCustomAttributes(typeof(ElementNameAttribute), false).Cast<ElementNameAttribute>().Any(c => c.ElementName.Equals(nodeName))); if (controlType == null) { throw new ControlNotSupportedException($"Control {nodeName} is not supported."); } IElement element = (IElement)Activator.CreateInstance(controlType, renderContext); foreach(XmlAttribute attribute in currentNode.Attributes) { // skip namespaced attributes, they belong to other implementations. if (attribute.Name.Contains(":")) continue; PropertyInfo property = controlType.GetProperties().SingleOrDefault(p => p.GetCustomAttributes(typeof(AttributeNameAttribute), false).Cast<AttributeNameAttribute>().Any(c => c.Name.Equals(attribute.Name))); if (property != null) { if (property.PropertyType == typeof(Boolean)) { property.SetValue(element, Boolean.Parse(attribute.Value)); } else { property.SetValue(element, attribute.Value); } } else { throw new AttributeNotSupportedException($"Control {nodeName} is does not support attribute {attribute.Name}."); } } IElementContainer container = element as IElementContainer; if (container != null) { var childNodes = currentNode.ChildNodes; foreach (XmlNode node in childNodes) { container.Elements.Add(CreateElement(renderContext, node, availableTypes)); } return container; } return element; }
private static void Generate( IEnumerable<TableDefinition> tableDefinitions, ProjectItem mappingsProjectItem, string templatePath) { // Create mapping files foreach (var tableDefinition in tableDefinitions) { var mappingFileName = TableDefinitionHelper.GetMappingFileName(tableDefinition) + ".cs"; mappingsProjectItem.ProjectItems.AddFromTemplate(templatePath, mappingFileName); } // Add mapping instructions foreach (ProjectItem projectItem in mappingsProjectItem.ProjectItems) { var name = projectItem.Name; var tableDefinition = tableDefinitions.SingleOrDefault(t => TableDefinitionHelper.GetMappingFileName(t) + ".cs" == name); var codeNamespace = CodeModelHelper.GetNameSpaceFromFileCode(projectItem.FileCodeModel); var fullNamespace = codeNamespace.FullName.Replace(NamespaceValues.Mappings, NamespaceValues.Models); // Add the import instructions. var fileCodeModel = (FileCodeModel2)projectItem.FileCodeModel; fileCodeModel.AddImport(fullNamespace); fileCodeModel.AddImport(NamespaceValues.OrmMappings); // Add inheritance to BaseMapping. var cls = CodeModelHelper.GetCodeClassFromFileCode(projectItem.FileCodeModel); cls.Access = vsCMAccess.vsCMAccessPublic; var fullyQualifiedName = string.Format("BaseMapping<{0}>", tableDefinition.TableName); cls.AddBase(fullyQualifiedName); // Modify the constructor cls.AddFunction(TableDefinitionHelper.GetMappingFileName(tableDefinition), vsCMFunction.vsCMFunctionConstructor, null, -1, vsCMAccess.vsCMAccessPublic, null); var constructor = (CodeFunction)cls.Children.Item(1); var startPoint = constructor.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint(); startPoint.StartOfLine(); startPoint.Indent(); startPoint.Insert("ToTable(\"" + tableDefinition.TableSchema + "." + tableDefinition.TableName + "\"); \n"); foreach (var columnDefinition in tableDefinition.ColumnDefinitions) { var statement = "Property(t => t." + columnDefinition.ColumnName + ").HasColumnName(\"" + columnDefinition.ColumnName + "\"); \n"; startPoint.Indent(Count: 3); startPoint.Insert(statement); } startPoint.EndOfLine(); startPoint.Indent(Count: 2); } }
public Story ParseBlocks(IEnumerable<Block> blocks) { // get the story var storyBlock = blocks.SingleOrDefault(b => b.Type == BlockType.Story); if(storyBlock == null) throw new FicdownException("No story block found"); Anchor storyAnchor; try { storyAnchor = Utilities.GetInstance(storyBlock.Name, storyBlock.LineNumber).ParseAnchor(storyBlock.Name); } catch(FicdownException ex) { throw new FicdownException(ex.BlockName, ex.LineNumber, "Story block must be an anchor pointing to the first scene"); } if (storyAnchor.Href.Target == null || storyAnchor.Href.Conditions != null || storyAnchor.Href.Toggles != null) throw new FicdownException(storyBlock.Name, storyBlock.LineNumber, "Story href should only have target"); var story = new Story { Name = storyAnchor.Text, Description = string.Join("\n", storyBlock.Lines.Select(l => l.Text)).Trim(), Scenes = new Dictionary<string, IList<Scene>>(), Actions = new Dictionary<string, Action>() }; var sid = 1; var scenes = blocks.Where(b => b.Type == BlockType.Scene).Select(b => BlockToScene(b, sid++)); foreach (var scene in scenes) { if (!story.Scenes.ContainsKey(scene.Key)) story.Scenes.Add(scene.Key, new List<Scene>()); story.Scenes[scene.Key].Add(scene); } var aid = 1; try { story.Actions = blocks.Where(b => b.Type == BlockType.Action).Select(b => BlockToAction(b, aid++)).ToDictionary(a => a.Toggle, a => a); } catch(ArgumentException) { var a = blocks.First(b => b.Type == BlockType.Action && blocks.Any(d => b != d && BlockToAction(b, 0).Toggle == BlockToAction(d, 0).Toggle)); var actionA = BlockToAction(a, a.LineNumber); var dupe = blocks.First(b => b.Type == BlockType.Action && b != a && BlockToAction(b, 0).Toggle == actionA.Toggle); throw new FicdownException(actionA.Toggle, actionA.LineNumber, string.Format("Action is defined again on line {0}", dupe.LineNumber)); } if (!story.Scenes.ContainsKey(storyAnchor.Href.Target)) throw new FicdownException(storyBlock.Name, storyBlock.LineNumber, string.Format("Story targets non-existent scene: {0}", storyAnchor.Href.Target)); story.FirstScene = storyAnchor.Href.Target; return story; }
private static List <XElement> GetEventsOnHtml(DateTime date, IEnumerable <IGrouping <DateTime, OnlineEvent> > eventsByDate) { var eventsOn = eventsByDate?.SingleOrDefault(e => e.Key.Date == date.Date)?.ToList(); if (eventsOn == null) { return(new List <XElement>()); } return(eventsOn.Count > 2 ? GetCellWithSummaryHtml(eventsOn) : GetCellWithEventsHtml(eventsOn)); }
private static string DetermineText(Constants expectedConnections, List <TcpConnectionInformation> knownConnections, string textMessage) { foreach (TcpConnectionInformation knownConn in knownConnections) { IPAddress slsr = knownConn.RemoteEndPoint.Address; IEnumerable <KeyValuePair <string, IPAddress> > match = expectedConnections.IPs .Where(pair => pair.Value.Equals(slsr)); textMessage += DateTime.Now.ToString() + " " + match?.SingleOrDefault().Key + IsConnected; } return(textMessage); }
/// <summary> /// Refresh an instance potentially from a different thread with a local context-tracked instance. /// </summary> /// <param name="obj">The object to use as a reference when negotiating a local instance.</param> /// <param name="lookupSource">An optional lookup source which will be used to query and populate a freshly retrieved replacement. If not provided, the refreshed object will still be returned but will not have any includes.</param> /// <typeparam name="T">A valid EF-stored type.</typeparam> protected virtual void Refresh <T>(ref T obj, IEnumerable <T> lookupSource = null) where T : class, IHasPrimaryKey { var context = GetContext(); if (context.Entry(obj).State != EntityState.Detached) { return; } var id = obj.ID; obj = lookupSource?.SingleOrDefault(t => t.ID == id) ?? context.Find <T>(id); }
private ResultadoValidacao Processar(IEnumerable <TurmaAluno> turmaAlunosModel, IEnumerable <TurmaAluno> turmaAlunosBancoDados, string turmaId) { if (string.IsNullOrEmpty(turmaId)) { throw new ArgumentNullException("O parâmetro turmaId não pode ser nulo ou vazio"); } var validacao = new ResultadoValidacao(); if (turmaAlunosModel != null) { if (turmaAlunosBancoDados != null) { // Verifica os registros removidos pelo usuario e remove da base de dados var registrosParaRemover = turmaAlunosBancoDados.Where(bd => !turmaAlunosModel.Select(m => m.Id).Contains(bd.Id)); registrosParaRemover.ToList().ForEach(x => repository.Remover(x)); } // Verifica a acao a ser tomada foreach (var TurmaAlunoModel in turmaAlunosModel) { // Se o model nao tiver id e um novo registro if (string.IsNullOrEmpty(TurmaAlunoModel.Id)) { validacao.AdicionarMensagens(this.Inserir(TurmaAlunoModel, turmaId)); } else { // Carrega o registro da base de dados com o mesmo id do enviado pelo model var TurmaAlunoBancoDados = turmaAlunosBancoDados?.SingleOrDefault(x => x.Id == TurmaAlunoModel.Id); // Se tem id e nao em correspondente na base de dados insere um novo registro pois pode ser um segundo usuario inserindo if (turmaAlunosBancoDados == null) { validacao.AdicionarMensagens(this.Inserir(TurmaAlunoModel, turmaId)); } else { // Se acho correspondente na base de dados atualiza as informacoes e grava validacao.AdicionarMensagens(this.Atualizar(TurmaAlunoModel, TurmaAlunoBancoDados)); } } } } else { turmaAlunosBancoDados?.ToList().ForEach(x => repository.Remover(x)); } return(validacao); }
private async Task AddFundingDatesToProfileTotals(ProfilePreviewRequest request, IEnumerable <ProfileTotal> profileTotals) { ApiResponse <FundingDate> fundingDateApiResponse = await _policiesResilience.ExecuteAsync(() => _policies.GetFundingDate(request.FundingStreamId, request.FundingPeriodId, request.FundingLineCode)); IEnumerable <FundingDatePattern> fundingDatePatterns = fundingDateApiResponse?.Content?.Patterns; foreach (ProfileTotal profileTotal in profileTotals ?? ArraySegment <ProfileTotal> .Empty) { profileTotal.ActualDate = fundingDatePatterns?.SingleOrDefault(_ => _.Occurrence == profileTotal.Occurrence && _.Period == profileTotal.TypeValue && _.PeriodYear == profileTotal.Year)?.PaymentDate; } }
/// <summary> /// This method is responsible for retrieving a project from the user, via the access token, by id from the Github API. /// </summary> /// <param name="accessToken">The access token which will be used to retrieve the correct project from the user.</param> /// <param name="projectId">The identifier of the project that will be used to search the correct project.</param> /// <returns>This method returns a project with this specified identifier.</returns> public async Task <Project> GetProjectById(string accessToken, string projectId) { IEnumerable <GithubDataSourceResourceResult> projects = await FetchAllGithubProjects(accessToken); GithubDataSourceResourceResult projectWithSpecifiedId = projects?.SingleOrDefault(resource => resource.Id.ToString() == projectId); if (projectWithSpecifiedId == null) { return(null); } Project p = mapper.Map <GithubDataSourceResourceResult, Project>(projectWithSpecifiedId); p.Description = await FetchReadme(projectWithSpecifiedId.Owner.Login, projectWithSpecifiedId.Name, accessToken) ?? p.Description; return(p); }
/// <summary> /// Post initialize this instance with a matching <see cref="ExceptionDescriptorAttribute"/> from the specified <paramref name="attributes"/>. /// </summary> /// <param name="attributes">The attributes to find a match within.</param> public void PostInitializeWith(IEnumerable <ExceptionDescriptorAttribute> attributes) { var attribute = attributes?.SingleOrDefault(eda => eda.FailureType == Failure.GetType()); if (attribute != null) { if (!attribute.Code.IsNullOrWhiteSpace()) { Code = attribute.Code; } if (!attribute.Message.IsNullOrWhiteSpace()) { Message = attribute.Message; } if (!attribute.HelpLink.IsNullOrWhiteSpace()) { HelpLink = new Uri(attribute.HelpLink); } } }
// no MapAll - take care private void Map(DocumentTypeSave source, DocumentTypeDisplay target, MapperContext context) { MapTypeToDisplayBase <DocumentTypeSave, PropertyTypeBasic, DocumentTypeDisplay, PropertyTypeDisplay>( source, target, context); // sync templates IEnumerable <string?> destAllowedTemplateAliases = target.AllowedTemplates.Select(x => x.Alias); // if the dest is set and it's the same as the source, then don't change if (source.AllowedTemplates is not null && destAllowedTemplateAliases.SequenceEqual(source.AllowedTemplates) == false) { IEnumerable <ITemplate>?templates = _fileService.GetTemplates(source.AllowedTemplates.ToArray()); target.AllowedTemplates = source.AllowedTemplates .Select(x => { ITemplate?template = templates?.SingleOrDefault(t => t.Alias == x); return(template != null ? context.Map <EntityBasic>(template) : null); }) .WhereNotNull() .ToArray(); } if (source.DefaultTemplate.IsNullOrWhiteSpace() == false) { // if the dest is set and it's the same as the source, then don't change if (target.DefaultTemplate == null || source.DefaultTemplate != target.DefaultTemplate.Alias) { ITemplate?template = _fileService.GetTemplate(source.DefaultTemplate); target.DefaultTemplate = template == null ? null : context.Map <EntityBasic>(template); } } else { target.DefaultTemplate = null; } }
/// <summary> /// Given a <see cref="IEnumerable{IMethodSymbol}"/>, this method returns the method symbol which /// matches the expectedParameterTypesInOrder parameter requirement /// </summary> /// <param name="members"></param> /// <param name="expectedParameterTypesInOrder"></param> /// <returns></returns> public static IMethodSymbol GetSingleOrDefaultMemberWithParameterInfos(this IEnumerable <IMethodSymbol> members, params ParameterInfo[] expectedParameterTypesInOrder) { var expectedParameterCount = expectedParameterTypesInOrder.Count(); return(members?.SingleOrDefault(member => { if (member.Parameters.Count() != expectedParameterCount) { return false; } for (int i = 0; i < expectedParameterCount; i++) { // check IsParams only on the last parameter if (i == expectedParameterCount - 1 && member.Parameters[i].IsParams != expectedParameterTypesInOrder[i].IsParams) { return false; } var parameterType = member.Parameters[i].Type; if (expectedParameterTypesInOrder[i].IsArray) { var arrayParameterSymbol = parameterType as IArrayTypeSymbol; if (arrayParameterSymbol?.Rank != expectedParameterTypesInOrder[i].ArrayRank) { return false; } parameterType = arrayParameterSymbol.ElementType; } if (!expectedParameterTypesInOrder[i].ParameterType.Equals(parameterType)) { return false; } } return true; })); }
public override IEnumerable <Task> ReadJson(JsonReader reader, Type objectType, IEnumerable <Task> existingValue, bool hasExistingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartObject) { return(null); } JObject root = JObject.Load(reader); ICollection <Task> workItems = new List <Task>(); foreach (JObject item in root["data"].Values <JObject>().AsEnumerable()) { Task workItem = existingValue?.SingleOrDefault(i => i.Id == item["id"].Value <string>()) ?? new Task(); workItem.Id = string.IsNullOrEmpty(workItem?.Id) ? item["id"].Value <long>().ToString() : workItem.Id; workItem.Type = string.IsNullOrEmpty(workItem?.Type) ? item["resource_type"].Value <string>() : workItem.Type; workItem.Title = string.IsNullOrEmpty(workItem?.Title) ? item["name"].Value <string>() : workItem.Title; workItems.Add(workItem); } return(workItems.AsEnumerable()); }
protected object GetValueFromRow(DataRow row, IColumnIdentifier identifier) { if (identifier is ColumnOrdinalIdentifier) { var ordinal = (identifier as ColumnOrdinalIdentifier).Ordinal; if (ordinal <= row.Table.Columns.Count) { return(row.ItemArray[ordinal]); } else { throw new ArgumentException($"The variable of the predicate is identified as '{identifier.Label}' but the column in position '{ordinal}' doesn't exist. The dataset only contains {row.Table.Columns.Count} columns."); } } var name = (identifier as ColumnNameIdentifier).Name; var alias = aliases?.SingleOrDefault(x => x.Name == name); if (alias != null) { return(row.ItemArray[alias.Column]); } var expression = expressions?.SingleOrDefault(x => x.Name == name); if (expression != null) { return(EvaluateExpression(expression, row)); } var column = row.Table.Columns.Cast <DataColumn>().SingleOrDefault(x => x.ColumnName == name); if (column != null) { return(row[column.ColumnName]); } throw new ArgumentException($"The value '{name}' is not recognized as a column name or a column position or a column alias or an expression."); }
/// <summary> /// Refresh an instance potentially from a different thread with a local context-tracked instance. /// </summary> /// <param name="obj">The object to use as a reference when negotiating a local instance.</param> /// <param name="lookupSource">An optional lookup source which will be used to query and populate a freshly retrieved replacement. If not provided, the refreshed object will still be returned but will not have any includes.</param> /// <typeparam name="T">A valid EF-stored type.</typeparam> protected virtual void Refresh <T>(ref T obj, IEnumerable <T> lookupSource = null) where T : class, IHasPrimaryKey { using (var usage = ContextFactory.GetForWrite()) { var context = usage.Context; if (context.Entry(obj).State != EntityState.Detached) { return; } var id = obj.ID; var foundObject = lookupSource?.SingleOrDefault(t => t.ID == id) ?? context.Find <T>(id); if (foundObject != null) { obj = foundObject; } else { context.Add(obj); } } }
public override IEnumerable <WorkItem> ReadJson(JsonReader reader, Type objectType, IEnumerable <WorkItem> existingValue, bool hasExistingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartObject) { return(null); } JObject root = JObject.Load(reader); IEnumerable <JToken> items = root["workItemRelations"].Values <JObject>().AsEnumerable().Select(item => item["target"]); ICollection <WorkItem> workItems = new List <WorkItem>(); foreach (JObject item in items) { WorkItem workItem = existingValue?.SingleOrDefault(i => i.Id == item["id"].Value <string>()) ?? new WorkItem(); workItem.Id = string.IsNullOrEmpty(workItem?.Id) ? item["id"].Value <string>() : workItem.Id; workItem.Url = string.IsNullOrEmpty(workItem?.Url) ? item["url"].Value <string>() : workItem.Url; workItems.Add(workItem); } return(workItems.AsEnumerable()); }
private static IssueStatus ToDto(this string state, IEnumerable <IssueState> states) { var mappedState = states?.SingleOrDefault(_ => state.Equals(_.Resource)); if (mappedState == null) { return(IssueStatus.Unknown); } switch (mappedState.Group) { case WorkItemStates.Open: return(IssueStatus.New); case WorkItemStates.Closed: return(IssueStatus.Closed); case WorkItemStates.InProgress: return(IssueStatus.Open); default: return(IssueStatus.Unknown); } }
/// <summary> /// Retrieve <see cref="Claims.Role"/> values from given collection of claims /// </summary> /// <param name="this">Collection of <see cref="Claim"/></param> /// <returns>String value from <see cref="Role"/></returns> public static string GetRoleValues(this IEnumerable <Claim> @this) { return(@this?.SingleOrDefault(x => x.Type.Contains(Claims.Role))?.Value); }
public Preference GetPreference(IEnumerable <Preference> preferences, string key) { return(preferences.SingleOrDefault(preference => preference.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase))); }
private static string GetValue(this IEnumerable <Claim> claims, string type) { var claim = claims?.SingleOrDefault(x => x.Type == type); return(claim?.Value); }
/// <summary> /// Retrieve <see cref="Claims.UserId"/> value from given collection of claims /// </summary> /// <param name="this">Collection of <see cref="Claim"/></param> /// <returns>String value from <see cref="Role"/></returns> public static string GetUserIdValue(this IEnumerable <Claim> @this) { return(@this?.SingleOrDefault(x => x.Type.Contains(Claims.UserId))?.Value); }
private async Task <Job> ParseJob(XElement jobXml) { var job = new Job() { Id = Int32.Parse(jobXml.Element("job_id").Value.Trim(), CultureInfo.InvariantCulture), Reference = HttpUtility.HtmlDecode(jobXml.Element("reference")?.Value).Trim(), NumberOfPositions = Int32.Parse(jobXml.Element("no_of_positions").Value, CultureInfo.InvariantCulture), JobTitle = HttpUtility.HtmlDecode(jobXml.Element("job_title").Value).Trim(), Department = HttpUtility.HtmlDecode(jobXml.Element("business_unit").Value).Trim().Replace("ESCC: ", string.Empty), Organisation = HttpUtility.HtmlDecode(jobXml.Element("region").Value).Trim(), DatePublished = new DateTime(Int32.Parse(jobXml.Element("open_date").Value.Substring(0, 4), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("open_date").Value.Substring(5, 2), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("open_date").Value.Substring(8, 2), CultureInfo.InvariantCulture)), ClosingDate = new DateTime(Int32.Parse(jobXml.Element("expiry_date").Value.Substring(0, 4), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("expiry_date").Value.Substring(5, 2), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("expiry_date").Value.Substring(8, 2), CultureInfo.InvariantCulture)) }; if (job.Department.ToUpperInvariant() == "PARTNERSHIP") { if (job.JobTitle.Contains("(") && job.JobTitle.EndsWith(")")) { var orgStarts = job.JobTitle.LastIndexOf("("); job.Organisation = job.JobTitle.Substring(orgStarts + 1).TrimEnd(')'); job.JobTitle = job.JobTitle.Substring(0, orgStarts).TrimEnd(); } else { job.Organisation = job.Department; } job.Department = string.Empty; } job.Locations.Add(HttpUtility.HtmlDecode(jobXml.Element("location_city").Value).Trim()); var logo = jobXml.Element("media")?.Element("logo")?.Element("url")?.Value; if (!String.IsNullOrEmpty(logo)) { // Ignore width and height from TribePad as they can be wrong! job.LogoUrl = new Uri(logo); } var advertHtml = new StringBuilder(); advertHtml.Append(HttpUtility.HtmlDecode(jobXml.Element("package_description")?.Value)); advertHtml.Append(HttpUtility.HtmlDecode(jobXml.Element("summary_external")?.Value)); advertHtml.Append(HttpUtility.HtmlDecode(jobXml.Element("main_responsibilities")?.Value)); job.AdvertHtml = new HtmlString(advertHtml.ToString()); job.AdditionalInformationHtml = new HtmlString(HttpUtility.HtmlDecode(jobXml.Element("ideal_candidate")?.Value)); job.EqualOpportunitiesHtml = new HtmlString(HttpUtility.HtmlDecode(jobXml.Element("about_company")?.Value)); job.JobType = HttpUtility.HtmlDecode(jobXml.Element("category_name")?.Value).Replace(" & ", " and "); if (jobXml.Element("no_apply")?.Value == "0") { job.ApplyUrl = new Uri(String.Format(CultureInfo.InvariantCulture, _applyUrl.ToString(), job.Id), UriKind.RelativeOrAbsolute); } job.Salary = await _salaryParser.ParseSalary(jobXml.ToString()); job.WorkPattern = await _workPatternParser.ParseWorkPattern(jobXml.ToString()); var contractTypeId = jobXml.Element("job_type")?.Value; if (!String.IsNullOrEmpty(contractTypeId)) { job.ContractType = _contractTypes?.SingleOrDefault(x => x.LookupValueId == contractTypeId)?.Text; } return(job); }
private bool ValidateCalculation(string argument, IEnumerable <Calculation> calculations) { return(calculations?.SingleOrDefault(x => x.Name == argument) != null); }
private async Task <Job> ParseJob(XElement jobXml) { var job = new Job() { Id = Int32.Parse(jobXml.Element("job_id").Value.Trim(), CultureInfo.InvariantCulture), Reference = HttpUtility.HtmlDecode(jobXml.Element("reference")?.Value).Trim(), NumberOfPositions = Int32.Parse(jobXml.Element("no_of_positions").Value, CultureInfo.InvariantCulture), JobTitle = HttpUtility.HtmlDecode(jobXml.Element("job_title").Value).Trim(), Department = HttpUtility.HtmlDecode(jobXml.Element("business_unit").Value).Trim().Replace("ESCC: ", string.Empty), Organisation = HttpUtility.HtmlDecode(jobXml.Element("region").Value).Trim(), DatePublished = new DateTime(Int32.Parse(jobXml.Element("open_date").Value.Substring(0, 4), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("open_date").Value.Substring(5, 2), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("open_date").Value.Substring(8, 2), CultureInfo.InvariantCulture)) }; var noClosingDate = jobXml.Element("evergreen")?.Value == "1"; if (!noClosingDate) { job.ClosingDate = new DateTime(Int32.Parse(jobXml.Element("expiry_date").Value.Substring(0, 4), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("expiry_date").Value.Substring(5, 2), CultureInfo.InvariantCulture), Int32.Parse(jobXml.Element("expiry_date").Value.Substring(8, 2), CultureInfo.InvariantCulture)); } var canApplyForThisJob = true; var comparableDepartment = job.Department.ToUpperInvariant(); if (comparableDepartment == "PARTNERSHIP") { canApplyForThisJob = false; if (!ParseAndMoveOrganisationFromJobTitle(job)) { job.Organisation = job.Department; } job.Department = string.Empty; } else if (comparableDepartment == "ESCC SCHOOLS" || comparableDepartment == "ESCC ACADEMIES") { if (ParseAndMoveOrganisationFromJobTitle(job)) { job.Department = string.Empty; } else { // If it's a school job but the school name is not in the job title, it's unknown job.Organisation = string.Empty; job.Department = string.Empty; } canApplyForThisJob = false; } else if (comparableDepartment == "CHILDREN SERVICES") { job.Department = "Children's Services"; } var locations = _locationParser.ParseLocations(jobXml.ToString()); if (locations != null) { foreach (var location in locations) { job.Locations.Add(location); } } var logo = jobXml.Element("media")?.Element("logo")?.Element("url")?.Value; if (!String.IsNullOrEmpty(logo)) { // Ignore width and height from TribePad as they can be wrong! job.LogoUrl = new Uri(logo); } var advertHtml = new StringBuilder(); advertHtml.Append(HttpUtility.HtmlDecode(jobXml.Element("package_description")?.Value)); advertHtml.Append(HttpUtility.HtmlDecode(jobXml.Element("summary_external")?.Value)); advertHtml.Append(HttpUtility.HtmlDecode(jobXml.Element("main_responsibilities")?.Value)); var files = jobXml.Element("files")?.Elements("file"); if (files != null) { if (files.Count() == 1) { advertHtml.Append("<h2>Documents</h2><p>").AppendLinkToFile(files.First(), job.Id).Append("</p>"); } else { advertHtml.Append("<h2>Documents</h2><ul>"); foreach (var file in files) { advertHtml.Append("<li>").AppendLinkToFile(file, job.Id).Append("</li>"); } advertHtml.Append("</ul>"); } } job.AdvertHtml = new HtmlString(advertHtml.ToString()); job.AdditionalInformationHtml = new HtmlString(HttpUtility.HtmlDecode(jobXml.Element("ideal_candidate")?.Value)); job.EqualOpportunitiesHtml = new HtmlString(HttpUtility.HtmlDecode(jobXml.Element("about_company")?.Value)); job.JobType = HttpUtility.HtmlDecode(jobXml.Element("category_name")?.Value)?.Replace(" & ", " and "); if (jobXml.Element("no_apply")?.Value == "0" && canApplyForThisJob) { job.ApplyUrl = new Uri(String.Format(CultureInfo.InvariantCulture, _applyUrl.ToString(), job.Id), UriKind.RelativeOrAbsolute); } job.Salary = await _salaryParser.ParseSalary(jobXml.ToString()).ConfigureAwait(false); job.WorkPattern = await _workPatternParser.ParseWorkPattern(jobXml.ToString()).ConfigureAwait(false); var contractTypeId = jobXml.Element("job_type")?.Value; if (!String.IsNullOrEmpty(contractTypeId)) { job.ContractType = _contractTypes?.SingleOrDefault(x => x.LookupValueId == contractTypeId)?.Text; } return(job); }
public async Task <Token> GetToken(string clientId, string refreshToken) { IEnumerable <Token> tokens = await _tokenRepository.FindAsync(t => t.ClientId == clientId && t.Value == refreshToken); return(tokens?.SingleOrDefault()); }
public static string GetUserIdFromClaims(this IEnumerable <Claim> claims) => claims?.SingleOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
private string GetNavFileByLanguage(string language) { return(_navFiles.SingleOrDefault(n => Path.GetFileNameWithoutExtension(n) == language) ?? _navFiles.SingleOrDefault(n => Path.GetFileNameWithoutExtension(n).ToLower() == "default")); }
private static void ProcessLocalizationHandback(Options options, string translationsPath, IEnumerable <string> validResourceFileNames, IEnumerable <string> locales) { var inputFilePath = options.InputFile; if (string.IsNullOrEmpty(inputFilePath)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No input file specified. Need input file to run in handback mode."); Console.ResetColor(); Environment.Exit(-1); } if (!File.Exists(inputFilePath)) { inputFilePath = Path.Combine(Environment.CurrentDirectory, inputFilePath); if (!File.Exists(inputFilePath)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Couldn't find the input file! Please use the -i flag."); Console.ResetColor(); Environment.Exit(-1); } } var fi = new FileInfo(inputFilePath); if (fi.Extension != ".csv") { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Only .csv file inputs supported. First column is english string, second is localized string."); Console.ResetColor(); Environment.Exit(-1); } if (locales.Any() && locales.Count() != 1) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("More than one locale specified. Please use one locale per localization handback."); Console.ResetColor(); Environment.Exit(-1); } // Set our handback locale var locale = locales.SingleOrDefault(); if (string.IsNullOrEmpty(locale)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Specified locale came up null for some reason. Aborting!"); Console.ResetColor(); Environment.Exit(-1); } var handbackMappings = new Dictionary <string, Dictionary <string, LocalizedString> >(); using (var textReader = File.OpenText(inputFilePath)) { CsvConfiguration config = new CsvConfiguration(); if (!string.IsNullOrEmpty(options.CsvDelimiter)) { config.Delimiter = options.CsvDelimiter; } var csv = new CsvReader(textReader, config); var handbackRecords = csv.GetRecords <LocalizedString>().ToList(); foreach (var obj in handbackRecords) { if (!handbackMappings.ContainsKey(obj.FileName)) { handbackMappings[obj.FileName] = new Dictionary <string, LocalizedString>(); } handbackMappings[obj.FileName][obj.FieldName] = obj; } } // Go through resource names foreach (var resourceName in validResourceFileNames) { // If we didn't get any resources for this file back in our handback file, then skip it if (!handbackMappings.ContainsKey(resourceName)) { continue; } var baselineResources = GetCultureResources(translationsPath, resourceName, s_baselineCulture); var localeResources = GetCultureResources(translationsPath, resourceName, locale); var handbackResources = handbackMappings[resourceName]; // Go through valid resource keys foreach (var baselineResource in baselineResources) { var resourceKey = baselineResource.Key; var baselineResourceValue = baselineResource.Value; // If we did not get a value for the current resource in the handback file, then skip it if (!handbackResources.ContainsKey(resourceKey)) { continue; } var handbackItem = handbackResources[resourceKey]; // Does the config specify that we ignore this value? if (s_config.Ignore.Contains(baselineResourceValue)) { // Let's see if it already exists, and remove it fromt he processing queue if so if (localeResources.ContainsKey(resourceKey)) { localeResources.Remove(resourceKey); } // Move on to next key continue; } string localeResourceValue = null; // Do we have any override translations? if (s_config.Custom.ContainsKey(locale) && s_config.Custom[locale].ContainsKey(baselineResourceValue)) { Console.WriteLine($"Settings string '{resourceKey}' ({baselineResourceValue}) to config override value"); localeResourceValue = s_config.Custom[locale][baselineResourceValue]; } if (!string.IsNullOrEmpty(localeResourceValue) && localeResourceValue != handbackItem.TranslatedString) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"localized string '{resourceKey}' ({baselineResourceValue}) is disallowed by the config. New Value is '{handbackItem.TranslatedString}'."); Console.ResetColor(); continue; } handbackResources.Remove(resourceKey); localeResourceValue = handbackItem.TranslatedString; // Add or update the value if (!localeResources.ContainsKey(resourceKey)) { localeResources.Add(resourceKey, localeResourceValue); } else { localeResources[resourceKey] = localeResourceValue; } } // Save changes off to the filesystem AddOrUpdateResourceFile(translationsPath, localeResources, resourceName, locale); } if (handbackMappings.Any()) { var outputFilePath = Path.Combine(Environment.CurrentDirectory, $"FailedTranslations-{DateTime.Now:MM.dd.yyyy}-{locale}-UTF8.csv"); using (var textWriter = new StreamWriter(outputFilePath, false, Encoding.UTF8)) { var csv = new CsvWriter(textWriter, GetConfiguration()); var items = handbackMappings.Select(obj => obj.Value).SelectMany(obj => obj.Values); // Add headers csv.WriteHeader <LocalizedString>(); foreach (var item in items) { csv.WriteRecord(item); } } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Not all translations were correctly matched. The remaining ({0}) localization have been written to a file for manual resolution.", handbackMappings.Count); Console.ResetColor(); Console.WriteLine(outputFilePath); Environment.Exit(-1); } }
public Task <ICustomEntityRoutingRule> ExecuteAsync(GetCustomEntityRoutingRuleByRouteFormatQuery query, IExecutionContext executionContext) { var routingRule = _customEntityRoutingRules.SingleOrDefault(r => r.RouteFormat == query.RouteFormat); return(Task.FromResult(routingRule)); }
private string DownloadFile(string fileName) { OSPlatform platform = _target.OperatingSystem; string filePath = null; if (SymbolService.IsSymbolStoreEnabled) { SymbolStoreKey key = null; if (platform == OSPlatform.Windows) { // It is the coreclr.dll's id (timestamp/filesize) in the DacInfo used to download the the dac module. if (_clrInfo.DacInfo.IndexTimeStamp != 0 && _clrInfo.DacInfo.IndexFileSize != 0) { key = PEFileKeyGenerator.GetKey(fileName, (uint)_clrInfo.DacInfo.IndexTimeStamp, (uint)_clrInfo.DacInfo.IndexFileSize); } else { Trace.TraceError($"DownloadFile: {fileName}: key not generated - no index timestamp/filesize"); } } else { // Use the runtime's build id to download the the dac module. if (!_clrInfo.DacInfo.ClrBuildId.IsDefaultOrEmpty) { byte[] buildId = _clrInfo.DacInfo.ClrBuildId.ToArray(); IEnumerable <SymbolStoreKey> keys = null; if (platform == OSPlatform.Linux) { keys = ELFFileKeyGenerator.GetKeys(KeyTypeFlags.DacDbiKeys, "libcoreclr.so", buildId, symbolFile: false, symbolFileName: null); } else if (platform == OSPlatform.OSX) { keys = MachOFileKeyGenerator.GetKeys(KeyTypeFlags.DacDbiKeys, "libcoreclr.dylib", buildId, symbolFile: false, symbolFileName: null); } else { Trace.TraceError($"DownloadFile: {fileName}: platform not supported - {platform}"); } key = keys?.SingleOrDefault((k) => Path.GetFileName(k.FullPathName) == fileName); } else { Trace.TraceError($"DownloadFile: {fileName}: key not generated - no index time stamp or file size"); } } if (key is not null) { // Now download the DAC module from the symbol server filePath = SymbolService.DownloadFile(key); } } else { Trace.TraceInformation($"DownLoadFile: {fileName}: symbol store not enabled"); } return(filePath); }