System.Collections.Generic.IEnumerable.SelectMany(System.Func, System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.SelectMany(System.Func, System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2183 Examples 7

19 Source : GhostEmote.cs
with MIT License
from 0x0ade

public static MTexture GetIcon(string emote, float time) {
            Atlas atlas;
            if ((atlas = GetIconAtlas(ref emote)) == null)
                return null;

            List<string> iconPaths = new(emote.Split(' '));
            if (iconPaths.Count > 1 && int.TryParse(iconPaths[0], out int fps)) {
                iconPaths.RemoveAt(0);
            } else {
                fps = 7; // Default FPS.
            }

            List<MTexture> icons = iconPaths.SelectMany(iconPath => {
                iconPath = iconPath.Trim();
                List<MTexture> subs = atlas.orig_GetAtlreplacedubtextures(iconPath);
                if (subs.Count != 0)
                    return subs;
                if (atlas.Has(iconPath))
                    return new List<MTexture>() { atlas[iconPath] };
                if (iconPath.ToLowerInvariant() == "end")
                    return new List<MTexture>() { null };
                return new List<MTexture>();
            }).ToList();

            if (icons.Count == 0)
                return null;

            if (icons.Count == 1)
                return icons[0];

            int index = (int) Math.Floor(time * fps);

            if (index >= icons.Count - 1 && icons[icons.Count - 1] == null)
                return icons[icons.Count - 2];

            return icons[index % icons.Count];
        }

19 Source : DbManager.cs
with MIT License
from 0x1000000

private static IReadOnlyList<TableRef> SortTablesByForeignKeys(Dictionary<TableRef, Dictionary<ColumnRef, ColumnModel>> acc)
        {
            var tableGraph = new Dictionary<TableRef, int>();
            var maxValue = 0;

            foreach (var pair in acc)
            {
                CountTable(pair.Key, pair.Value, 1);
            }

            return acc
                .Keys
                .OrderByDescending(k => tableGraph.TryGetValue(k, out var value) ? value : maxValue)
                .ThenBy(k => k)
                .ToList();

            void CountTable(TableRef table, Dictionary<ColumnRef, ColumnModel> columns, int value)
            {
                var parentTables = columns.Values
                    .Where(c => c.Fk != null)
                    .SelectMany(c => c.Fk!)
                    .Select(f => f.Table)
                    .Distinct()
                    .Where(pt => !pt.Equals(table))//Self ref
                    .ToList();

                bool hasParents = false;
                foreach (var parentTable in parentTables)
                {
                    if (tableGraph.TryGetValue(parentTable, out int oldValue))
                    {
                        if (value >= 1000)
                        {
                            throw new SqExpressCodeGenException("Cycle in tables");
                        }

                        if (oldValue < value)
                        {
                            tableGraph[parentTable] = value;
                        }
                    }
                    else
                    {
                        tableGraph.Add(parentTable, value);
                    }

                    if (maxValue < value)
                    {
                        maxValue = value;
                    }

                    CountTable(parentTable, acc[parentTable], value + 1);
                    hasParents = true;
                }

                if (hasParents && !tableGraph.ContainsKey(columns.Keys.First().Table))
                {
                    tableGraph.Add(table, 0);
                }
            }
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream NeuterAutoOpenCells()
        {
            List<Lbl> autoOpenLbls = WbStream.GetAutoOpenLabels();

            List<BOF> macroSheetBofs = WbStream.GetMacroSheetBOFs();

            List<BiffRecord> macroSheetRecords =
                macroSheetBofs.SelectMany(bof => WbStream.GetRecordsForBOFRecord(bof)).ToList();

            List<BiffRecord> macroFormulaRecords = macroSheetRecords.Where(record => record.Id == RecordType.Formula).ToList();
            List<Formula> macroFormulas = macroFormulaRecords.Select(r => r.AsRecordType<Formula>()).ToList();

            foreach (Lbl autoOpenLbl in autoOpenLbls)
            {
                int autoOpenRw, autoOpenCol;
                switch (autoOpenLbl.rgce.First())
                {
                    case PtgRef3d ptgRef3d:
                        autoOpenCol = ptgRef3d.col;
                        autoOpenRw = ptgRef3d.rw;
                        break;
                    case PtgRef ptgRef:
                        autoOpenRw = ptgRef.rw;
                        autoOpenCol = ptgRef.col;
                        break;
                    default:
                        throw new NotImplementedException("Auto_Open Ptg Expressions that aren't PtgRef or PtgRef3d Not Implemented");
                }

                //TODO Add proper sheet referencing here so we don't just grab them all
                List<Formula> matchingFormulas =
                    macroFormulas.Where(f => f.col == autoOpenCol && f.rw == autoOpenRw).ToList();

                foreach (var matchingFormula in matchingFormulas)
                {
                    //TODO [Bug] This will currently break the entire sheet from loading. Not COMPLETED
                    Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>();
                    ptgStack.Push(new PtgConcat());
                    AbstractPtg[] ptgArray = matchingFormula.ptgStack.Reverse().ToArray();
                    foreach (var elem in ptgArray)
                    {
                        ptgStack.Push(elem);
                    }
                    ptgStack.Push(new PtgFunc(FtabValues.HALT, AbstractPtg.PtgDataType.VALUE));
                    Formula clonedFormula = ((BiffRecord) matchingFormula.Clone()).AsRecordType<Formula>();
                    clonedFormula.SetCellParsedFormula(new CellParsedFormula(ptgStack));

                    WbStream = WbStream.ReplaceRecord(matchingFormula, clonedFormula);
                }
            }

            return WbStream;
        }

19 Source : SimCluster.cs
with MIT License
from abdullin

public IEnumerable<SimService> Filter(Predicate<ServiceId> filter) {
            if (null == filter) {
                return Machines.SelectMany(p => p.Value.Services.Values);
            }

            return Machines.SelectMany(p => p.Value.Services.Values).Where(p => filter(p.Id));
        }

19 Source : ObjectManipulatorInspector.cs
with Apache License 2.0
from abist-co-ltd

public override void OnInspectorGUI()
        {
            EditorGUILayout.PropertyField(hostTransform);
            EditorGUILayout.PropertyField(manipulationType);
            EditorGUILayout.PropertyField(allowFarManipulation);

            var handedness = (ManipulationHandFlags)manipulationType.intValue;

            EditorGUILayout.Space();
            GUIStyle style = EditorStyles.foldout;
            FontStyle previousStyle = style.fontStyle;
            style.fontStyle = FontStyle.Bold;
            oneHandedFoldout = EditorGUILayout.Foldout(oneHandedFoldout, "One Handed Manipulation", true);

            if (oneHandedFoldout)
            {
                if (handedness.HasFlag(ManipulationHandFlags.OneHanded))
                {
                    EditorGUILayout.PropertyField(oneHandRotationModeNear);
                    EditorGUILayout.PropertyField(oneHandRotationModeFar);
                }
                else
                {
                    EditorGUILayout.HelpBox("One handed manipulation disabled. If you wish to enable one handed manipulation select it as a Manipulation Type above.", MessageType.Info);
                }
            }

            EditorGUILayout.Space();
            twoHandedFoldout = EditorGUILayout.Foldout(twoHandedFoldout, "Two Handed Manipulation", true);

            if (twoHandedFoldout)
            {
                if (handedness.HasFlag(ManipulationHandFlags.TwoHanded))
                {
                    EditorGUILayout.PropertyField(twoHandedManipulationType);
                }
                else
                {
                    EditorGUILayout.HelpBox("Two handed manipulation disabled. If you wish to enable two handed manipulation select it as a Manipulation Type above.", MessageType.Info);
                }
            }

            var mh = (ObjectManipulator)target;
            var rb = mh.HostTransform.GetComponent<Rigidbody>();

            EditorGUILayout.Space();
            constraintsFoldout = EditorGUILayout.Foldout(constraintsFoldout, "Constraints", true);

            if (constraintsFoldout)
            {
                if (EditorGUILayout.DropdownButton(new GUIContent("Add Constraint"), FocusType.Keyboard))
                {
                    // create the menu and add items to it
                    GenericMenu menu = new GenericMenu();

                    var type = typeof(TransformConstraint);
                    var types = AppDomain.CurrentDomain.Getreplacedemblies()
                        .SelectMany(s => s.GetLoadableTypes())
                        .Where(p => type.IsreplacedignableFrom(p));

                    foreach (var derivedType in types)
                    {
                        menu.AddItem(new GUIContent(derivedType.Name), false, t => mh.gameObject.AddComponent((Type)t), derivedType);
                    }

                    menu.ShowAsContext();
                }

                var constraints = mh.GetComponents<TransformConstraint>();

                foreach (var constraint in constraints)
                {
                    EditorGUILayout.BeginHorizontal();
                    string constraintName = constraint.GetType().Name;
                    EditorGUILayout.LabelField(constraintName);
                    if (GUILayout.Button("Go to component"))
                    {
                        Highlighter.Highlight("Inspector", $"{ObjectNames.NicifyVariableName(constraintName)} (Script)");
                        EditorGUIUtility.ExitGUI();
                    }
                    EditorGUILayout.EndHorizontal();
                }
            }

            EditorGUILayout.Space();
            physicsFoldout = EditorGUILayout.Foldout(physicsFoldout, "Physics", true);

            if (physicsFoldout)
            {
                if (rb != null)
                {
                    EditorGUILayout.PropertyField(releaseBehavior);
                }
                else
                {
                    EditorGUILayout.HelpBox("Physics options disabled. If you wish to enable physics options, add a Rigidbody component to this object.", MessageType.Info);
                }
            }

            EditorGUILayout.Space();
            smoothingFoldout = EditorGUILayout.Foldout(smoothingFoldout, "Smoothing", true);

            if (smoothingFoldout)
            {
                EditorGUILayout.PropertyField(smoothingActive);
                EditorGUILayout.PropertyField(moveLerpTime);
                EditorGUILayout.PropertyField(rotateLerpTime);
                EditorGUILayout.PropertyField(scaleLerpTime);
            }

            EditorGUILayout.Space();
            eventsFoldout = EditorGUILayout.Foldout(eventsFoldout, "Manipulation Events", true);

            if (eventsFoldout)
            {
                EditorGUILayout.PropertyField(onManipulationStarted);
                EditorGUILayout.PropertyField(onManipulationEnded);
                EditorGUILayout.PropertyField(onHoverEntered);
                EditorGUILayout.PropertyField(onHoverExited);
            }

            // reset foldouts style
            style.fontStyle = previousStyle;

            serializedObject.ApplyModifiedProperties();
        }

19 Source : GroupingByFeature.cs
with MIT License
from ABTSoftware

public ObservableCollection<TileViewModel> GroupingPredicate(IDictionary<Guid, Example> examples)
        {
            var temp = examples.SelectMany(pair =>
            {
                var l = new List<Tuple<Features, Example>>();
                pair.Value.Features.ForEach(feature => l.Add(new Tuple<Features, Example>(feature, pair.Value)));
                return l;
            });
            
            var groups = temp.OrderBy(pair => pair.Item1.ToString()).GroupBy(pair => pair.Item1);

            var result = new ObservableCollection<TileViewModel>();
            foreach (IGrouping<Features, Tuple<Features, Example>> pairs in groups)
            {
                result.Add(new TileViewModel
                {
                    TileDataContext = new EverythingGroupViewModel {GroupingName = pairs.Key.ToString()}
                });
                foreach (var example in pairs.Select(x => x.Item2))
                {
                    result.Add(new TileViewModel { TileDataContext = example });
                }
            }

            return result;
        }

19 Source : ForbiddenFieldsInDacAnalyzer.cs
with GNU General Public License v3.0
from Acumatica

public override void replacedyze(SymbolreplacedysisContext context, PXContext pxContext, DacSemanticModel dacOrDacExtension)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			string[] forbiddenNames = GetForbiddenFieldsNames();
			var invalidProperties = from forbiddenFieldName in forbiddenNames
									where dacOrDacExtension.PropertiesByNames.ContainsKey(forbiddenFieldName)
									select dacOrDacExtension.PropertiesByNames[forbiddenFieldName];

			foreach (DacPropertyInfo property in invalidProperties.Where(p => p.Symbol.ContainingSymbol == dacOrDacExtension.Symbol))
			{
				RegisterDiagnosticForIdentifier(property.Node.Identifier, pxContext, context);
			}

			context.CancellationToken.ThrowIfCancellationRequested();
			var allNestedTypesDictionary = dacOrDacExtension.GetMemberNodes<ClreplacedDeclarationSyntax>()
															.ToLookup(node => node.Identifier.ValueText, StringComparer.OrdinalIgnoreCase);
			var allInvalidFields = forbiddenNames.Where(forbiddenClreplacedName => allNestedTypesDictionary.Contains(forbiddenClreplacedName))
												 .SelectMany(forbiddenClreplacedName => allNestedTypesDictionary[forbiddenClreplacedName]);

			foreach (ClreplacedDeclarationSyntax fieldNode in allInvalidFields)
			{
				RegisterDiagnosticForIdentifier(fieldNode.Identifier, pxContext, context);
			}
		}

19 Source : PXGraphEventSemanticModel.cs
with GNU General Public License v3.0
from Acumatica

private IEnumerable<IMethodSymbol> GetAllGraphMethodsFromBaseToDerived()
		{
			IEnumerable<ITypeSymbol> baseTypes = BaseGraphModel.GraphSymbol
															   .GetGraphWithBaseTypes()
															   .Reverse();

			if (BaseGraphModel.Type == GraphType.PXGraphExtension)
			{
				baseTypes = baseTypes.Concat(
										BaseGraphModel.Symbol.GetGraphExtensionWithBaseExtensions(_pxContext, 
																								  SortDirection.Ascending,
																								  includeGraph: false));
			}

			return baseTypes.SelectMany(t => t.GetMembers().OfType<IMethodSymbol>());
		}

19 Source : ITypeSymbolExtensions.cs
with GNU General Public License v3.0
from Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static IEnumerable<ITypeSymbol> GetAllAttributesDefinedOnThisAndBaseTypes(this ITypeSymbol typeSymbol)
		{
			typeSymbol.ThrowOnNull(nameof(typeSymbol));
			return typeSymbol.GetBaseTypesAndThis()
							 .SelectMany(t => t.GetAttributes())
							 .Select(a => a.AttributeClreplaced);
		}

19 Source : Grammar.cs
with MIT License
from adamant

public void Validate()
        {
            foreach (var rule in Rules.Where(IsLeaf))
            {
                var baseNonTerminalPropertyNames
                    = AncestorRules(rule)
                      .SelectMany(r => r.Properties)
                      .Where(IsNonTerminal).Select(p => p.Name);
                var nonTerminalPropertyNames = rule.Properties.Where(IsNonTerminal).Select(p => p.Name);
                var missingProperties = baseNonTerminalPropertyNames.Except(nonTerminalPropertyNames).ToList();
                if (missingProperties.Any())
                    throw new ValidationException($"Rule for {rule.Nonterminal} is missing inherited properties: {string.Join(", ", missingProperties)}. Can't determine order to visit children.");
            }
        }

19 Source : EnumerableExtensions.cs
with MIT License
from adamant

[DebuggerStepThrough]
        public static IEnumerable<TResult> CrossJoin<TFirst, TSecond, TResult>(
            this IEnumerable<TFirst> first,
            IEnumerable<TSecond> second,
            Func<TFirst, TSecond, TResult> resultSelector)
        {
            return first.SelectMany(_ => second, resultSelector);
        }

19 Source : EnumerableExtensions.cs
with MIT License
from adamant

[DebuggerStepThrough]
        public static IEnumerable<(TFirst, TSecond)> CrossJoin<TFirst, TSecond>(
            this IEnumerable<TFirst> first,
            IEnumerable<TSecond> second)
        {
            return first.SelectMany(_ => second, (f, s) => (f, s));
        }

19 Source : ReachabilityGraphGraphvizExtensions.cs
with MIT License
from adamant

private static void AppendBorrows(
            StringBuilder dot,
            IReadOnlyList<MemoryPlace> places,
            Dictionary<IReference, string> referenceNames)
        {
            var borrowedReferences = places.SelectMany(n => n.References)
                                           .Where(r => r.Borrowers.Any()).ToList();

            if (borrowedReferences.Any())
            {
                dot.AppendLine("    node [shape=circle,width=0.05,label=\"\"];");
                dot.AppendLine("    edge [dir=forward,style=dashed];");
            }

            foreach (var borrowed in borrowedReferences)
            {
                var borrowedName = AppendBorrowPoint(dot, borrowed, referenceNames);
                foreach (var borrower in borrowed.Borrowers)
                {
                    var borrowerName = AppendBorrowPoint(dot, borrower, referenceNames);
                    var color = borrower.IsUsed || borrower.IsUsedForBorrow() ? Black : Grey;
                    dot.AppendLine($"    {borrowedName} -> {borrowerName} [color=\"{color}:{color}\"];");
                }
            }
        }

19 Source : PublishingStateTransitionSecurityProvider.cs
with MIT License
from Adoxio

public bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy website, Guid fromStateId, Guid toStateId)
		{
			// Windows Live ID Server decided to return null for an unauthenticated user's name
			// A null username, however, breaks the Roles.GetRolesForUser() because it expects an empty string.
			var currentUsername = (HttpContext.Current.User != null && HttpContext.Current.User.Idenreplacedy != null)
				? HttpContext.Current.User.Idenreplacedy.Name ?? string.Empty
				: string.Empty;

			var userRoles = Roles.GetRolesForUser(currentUsername).ToLookup(role => role);

			//Get publshing state transitional rules 
			var publishingStateRulesApplicable = context.CreateQuery("adx_publishingstatetransitionrule").Where(psr =>
				psr.GetAttributeValue<EnreplacedyReference>("adx_fromstate_publishingstateid") == new EnreplacedyReference("adx_publishingstate", fromStateId) &&
				psr.GetAttributeValue<EnreplacedyReference>("adx_tostate_publishingstateid") == new EnreplacedyReference("adx_publishingstate", toStateId) &&
				psr.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == website.ToEnreplacedyReference()).ToList();

			var webRoles = publishingStateRulesApplicable.SelectMany(rule => rule.GetRelatedEnreplacedies(context, "adx_publishingstatetransitionrule_webrole")
				.Where(role => role.GetAttributeValue<EnreplacedyReference>("adx_websiteid") != null && role.GetAttributeValue<EnreplacedyReference>("adx_websiteid").Id == website.Id))
					.ToList().Select(role => role.GetAttributeValue<string>("adx_name"));

			// Determine if the user belongs to any of the roles that apply to this rule grouping
			// If the user belongs to one of the roles... or if there are no rules applicable
			return (!publishingStateRulesApplicable.Any()) || webRoles.Any(role => userRoles.Contains(role));
		}

19 Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio

private static IEnumerable<XElement> GetContent(IEnumerable<ChangeMonitorDetail> monitors)
		{
			var keys = monitors.SelectMany(cm => cm.CacheKeys).Select(key => new XElement("cacheEntry", key));

			return keys;
		}

19 Source : WebPageAccessControlSecurityProvider.cs
with MIT License
from Adoxio

public virtual bool Tryreplacedert(WebPageNode page, CrmEnreplacedyRight right, bool useScope)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on web page '{1}' ({2}).", right, page.Name, page.Id));

			if (!Roles.Enabled)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");

				// If roles are not enabled on the site, grant Read, deny Change.
				return right == CrmEnreplacedyRight.Read;
			}

			// Ignore access control rules for service pages like not found or access denied
			if (right == CrmEnreplacedyRight.Read && IsServicePage(page))
			{
				return true;
			}

			// If the chain of pages from the current page up to the root page contains an inactive page, deny the replacedertion
			if (IsInactivePath(page))
			{
				return false;
			}

			var userRoles = this.GetUserRoles();

			// when we use rule scope we're checking permissions for parent page of web file
			//	and we need to check permissions only for one level
			var useInheritance = !useScope || right == CrmEnreplacedyRight.Change;

			// Get all rules applicable to the page and its parent path, grouping equivalent rules. (Rules that
			// target the same web page and confer the same right are equivalent.)
			var ruleGroupings =
				from rule in this.GetRulesApplicableToWebPage(page, useInheritance)
				where rule.WebPage != null && rule.Right != null
				group rule by new { WebPageId = rule.WebPage.Id, Right = ParseRightOption(rule.Right.Value) } into ruleGrouping
				select ruleGrouping;

			// Order the rule groupings so that all GrantChange rules will be evaluated first.
			ruleGroupings = ruleGroupings.OrderByDescending(grouping => grouping.Key.Right, new RightOptionComparer());

			foreach (var ruleGrouping in ruleGroupings)
			{
				// Collect the names of all the roles that apply to this rule grouping
				var ruleGroupingRoles = ruleGrouping.SelectMany(
					rule => rule.WebRoles.Where(role => BelongsToWebsite(page.Website, role))
					.Select(role => role.Name));

				// Determine if the user belongs to any of the roles that apply to this rule grouping
				var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));

				// If the user belongs to one of the roles...
				if (userIsInAnyRoleForThisRule)
				{
					// ...and the rule is GrantChange...
					if (ruleGrouping.Key.Right == RightOption.GrantChange)
					{
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on web page ({0}). Permission granted.", ruleGrouping.Key.WebPageId));

						// ...the user has all rights.
						return true;
					}
				}

				// If the user does not belong to any of the roles, the rule restricts read, and the desired right
				// is read...
				else if (ruleGrouping.Key.Right == RightOption.RestrictRead && right == CrmEnreplacedyRight.Read)
				{
					if (useScope && ruleGrouping.Any(rule => rule.Scope.HasValue && (ScopeOption)rule.Scope.Value == ScopeOption.ExcludeDirectChildWebFiles))
					{
						// Ignore read restriction for web files where scope is ExcludeDirectChildWebFiles
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Ignoring web page ({0}) read restriction due to ExcludeDirectChildWebFiles", ruleGrouping.Key.WebPageId));
					}
					else
					{
						if (page.Parent == null && page.PartialUrl == "/")
						{
							ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("\"Restrict Read\" right on web page({0}) ({1}).", ruleGrouping.Key.WebPageId, page.Name));
						}
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on web page ({0}). Permission denied.", ruleGrouping.Key.WebPageId));

						// ...the user has no right.
						return false;
					}
				}
			}

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and page. Allowing Read, but not Change.");

			// If none of the above rules apply, grant Read by default, and deny Change by default.
			return right == CrmEnreplacedyRight.Read;
		}

19 Source : EventAggregationDataAdapter.cs
with MIT License
from Adoxio

public IEnumerable<IEventOccurrence> SelectEventOccurrences(DateTime min, DateTime max)
		{
			var serviceContext = Dependencies.GetServiceContext();
			var security = Dependencies.GetSecurityProvider();

			return SelectEvents()
				.SelectMany(e => e.GetRelatedEnreplacedies(serviceContext, "adx_event_eventschedule")
					.Where(es => security.Tryreplacedert(serviceContext, es, CrmEnreplacedyRight.Read))
					.Select(es => new { Event = e, EventSchedule = es }))
				.SelectMany(e => serviceContext.GetDates(e.EventSchedule, min, max)
					.Select(d => new { e.Event, e.EventSchedule, Start = d }))
				.Select(e => new EventOccurrence(
					e.Event,
					e.EventSchedule,
					e.Start,
					GetEventOccurrenceUrl(serviceContext, e.Event, e.EventSchedule, e.Start),
					GetEventOccurrenceLocation(e.Event)))
				.OrderBy(e => e.Start)
				.ToArray();
		}

19 Source : EventAccessPermissionProvider.cs
with MIT License
from Adoxio

public override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy currentEvent, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies)
		{
			currentEvent.replacedertEnreplacedyName("adx_event");

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on event ({1}).", right, currentEvent.Id));

			dependencies.AddEnreplacedyDependency(currentEvent);
			dependencies.AddEnreplacedySetDependency("adx_webrole");
			dependencies.AddEnreplacedySetDependency("adx_eventaccesspermission");

			if (!Roles.Enabled)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");

                // If roles are not enabled on the site, grant Read, deny Change.
                return (right == CrmEnreplacedyRight.Read);
			}

			// Windows Live ID Server decided to return null for an unauthenticated user's name
			// A null username, however, breaks the Roles.GetRolesForUser() because it expects an empty string.
			var currentUsername = (HttpContext.Current.User != null && HttpContext.Current.User.Idenreplacedy != null)
				? HttpContext.Current.User.Idenreplacedy.Name ?? string.Empty
				: string.Empty;
			

			var userRoles = Roles.GetRolesForUser(currentUsername);

			// Get all rules applicable to the event, grouping equivalent rules. (Rules that
			// target the same event and confer the same right are equivalent.)
			var ruleGroupings = from rule in GetRulesApplicableToEvent(context, currentEvent, dependencies)
								let eventReference = rule.GetAttributeValue<EnreplacedyReference>("adx_eventid")
								let rightOption = rule.GetAttributeValue<OptionSetValue>("adx_right")
								where eventReference != null && rightOption != null
								group rule by new { EventID = eventReference.Id, Right = rightOption.Value } into ruleGrouping
								select ruleGrouping;

			var websiteReference = currentEvent.GetAttributeValue<EnreplacedyReference>("adx_websiteid");

			foreach (var ruleGrouping in ruleGroupings)
			{
				// Collect the names of all the roles that apply to this rule grouping
				var ruleGroupingRoles = ruleGrouping.SelectMany(rule => rule.GetRelatedEnreplacedies(context, "adx_eventaccesspermission_webrole").ToList()
					.Where(role => BelongsToWebsite(websiteReference, role))
					.Select(role => role.GetAttributeValue<string>("adx_name")));

				// Determine if the user belongs to any of the roles that apply to this rule grouping
				var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));

				// If the user belongs to one of the roles...
				if (userIsInAnyRoleForThisRule)
				{
					if (ruleGrouping.Key.Right != RestrictRead)
					{
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on forum ({0}). Permission granted.", ruleGrouping.Key.EventID));

						// ...the user has all rights.
						return true;
					}
				}
				// If the user does not belong to any of the roles, the rule restricts read, and the desired right
				// is read...
				else if (ruleGrouping.Key.Right == RestrictRead && right == CrmEnreplacedyRight.Read)
				{
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on event ({0}). Permission denied.", ruleGrouping.Key.EventID));

					// ...the user has no right.
					return false;
				}
			}
			
			//Get all membership type applicable to the event
			var membershipTypes = currentEvent.GetRelatedEnreplacedies(context, "adx_event_membershiptype");

			//If the event has membership types, specific user has right to access it. If there is no membership type, every user has right.
			if (membershipTypes.Any())
			{
				var contact = PortalContext.Current.User;

				//Anonymouse user has no right.
				if (contact == null) return false;

				foreach (var membershipType in membershipTypes)
				{
					if (contact.GetRelatedEnreplacedies(context, "adx_membership_contact").Any(m => m.GetAttributeValue<EnreplacedyReference>("adx_membershiptypeid") == membershipType.ToEnreplacedyReference()))                   
					{
						return true;
					}
				}

				return false;
			}

			// If none of the above rules apply, replacedert on parent webpage.
			var parentWebPage = currentEvent.GetRelatedEnreplacedy(context, "adx_webpage_event");

			// If there is no parent web page, grant Read by default, and deny Change.
			if (parentWebPage == null)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and event. Allowing Read, but not Change.");

				return (right == CrmEnreplacedyRight.Read);
			}

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and event. replacederting right on parent web page.");

			return _webPageAccessControlProvider.Tryreplacedert(context, parentWebPage, right, dependencies);
		}

19 Source : CmsIndexHelper.cs
with MIT License
from Adoxio

private static IEnumerable<string> SelectAllForumsWebRoles(Guid enreplacedyId, ContentMap contentMap)
		{
			EnreplacedyNode enreplacedy;

			// Get the Forums from the content map
			if (!contentMap.TryGetValue(new EnreplacedyReference("adx_communityforum", enreplacedyId), out enreplacedy))
			{
				return Enumerable.Empty<string>();
			}

			var forum = enreplacedy as ForumNode;
			if (forum == null)
			{
				return Enumerable.Empty<string>();
			}

			var changeRules =
				forum.ForumAccessPermissions.Where(fa => fa.Right == ForumAccessPermissionNode.RightOption.GrantChange)
					.SelectMany(fa => fa.WebRoles.Select(wr => wr.Name));

			var readRules =
				forum.ForumAccessPermissions.Where(fa => fa.Right == ForumAccessPermissionNode.RightOption.RestrictRead)
					.SelectMany(fa => fa.WebRoles.Select(wr => wr.Name)).ToList();

			bool anyInheritedReadRestrictRules = false;

			// If it has a parent page we will need to inspect to see if they have different read rules.
			if (forum.ParentPage != null)
			{
				var parentPageWebRoles = GetRulesForPage(forum.ParentPage).Distinct().ToList();
				anyInheritedReadRestrictRules =
				parentPageWebRoles.Any(
					rule =>
					{
						if (rule.Right == null)
						{
							return false;
						}
						return rule.Right.Value.ToEnum<ForumAccessPermissionProvider.RightOption>()
						   == ForumAccessPermissionProvider.RightOption.RestrictRead;
					});

				// If Both the webpage tree do not have read restrict rules then give access to all.  
				var parentPageWebRoleNames = anyInheritedReadRestrictRules || readRules.Any()
						? parentPageWebRoles.SelectMany(
							webPageAccessControlRuleNode => webPageAccessControlRuleNode.WebRoles,
								(webPageAccessControlRuleNode, webRole) => webRole.Name).Distinct()
						: new[] { AllowAccessDefaultValue };

				// If there are no read restrict rules then we just follow the parents roles and change roles
				if (!readRules.Any() && !anyInheritedReadRestrictRules)
				{
					return changeRules.Concat(parentPageWebRoleNames).Distinct();
				}

				readRules = parentPageWebRoleNames.Union(readRules).ToList();
			}

			// Since it didn't have a parent page make sure there isn't a read restrict rule if no then give access to all. 
			return readRules.Any() || anyInheritedReadRestrictRules ? changeRules.Concat(readRules).Distinct() : new[] { AllowAccessDefaultValue };
		}

19 Source : CmsIndexHelper.cs
with MIT License
from Adoxio

private static IEnumerable<string> SelectAllWebRolesForWebpage(Guid enreplacedyId, ContentMap contentMap)
		{
			EnreplacedyNode enreplacedy;
			if (!contentMap.TryGetValue(new EnreplacedyReference("adx_webpage", enreplacedyId), out enreplacedy))
			{
				return Enumerable.Empty<string>();
			}

			var webpage = enreplacedy as WebPageNode;
			if (webpage == null)
			{
				return Enumerable.Empty<string>();
			}
			var webAccessRules = GetRulesForPage(webpage).ToList();

			// If the rule doesn't have a right replacedociated to it then allow access 
			var anyReadRestrictRules =
				webAccessRules.Any(
					rule =>
						{
							if (rule.Right == null)
							{
								return false;
							}
							return rule.Right.Value.ToEnum<ForumAccessPermissionProvider.RightOption>()
							   == ForumAccessPermissionProvider.RightOption.RestrictRead;
						});

			// If there is not read restrict rules specified then allow READ access. 
			return anyReadRestrictRules || (webpage.PublishingState.IsVisible == null || webpage.PublishingState.IsVisible.Value == false) 
					? webAccessRules.SelectMany(webPageAccessControlRuleNode => webPageAccessControlRuleNode.WebRoles,
						(webPageAccessControlRuleNode, webRole) => webRole.Name).Distinct() 
					: new[] { AllowAccessDefaultValue };
		}

19 Source : CrmEntityIndexBuilder.cs
with MIT License
from Adoxio

private void UpdateWithIndexers(string enreplacedyLogicalName, IEnumerable<ICrmEnreplacedyIndexer> indexers)
		{
			if (!indexers.Any(indexer => indexer.Indexes(enreplacedyLogicalName)))
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Application does not index enreplacedy {0}. No update performed.", enreplacedyLogicalName));

				return;
			}

			var enreplacedyIndexDoreplacedents = indexers.SelectMany(indexer => indexer.GetDoreplacedents()).ToArray();

			UsingWriter(MethodBase.GetCurrentMethod().Name, false, true, writer =>
			{
				foreach (var enreplacedyDoc in enreplacedyIndexDoreplacedents)
				{
					writer.DeleteDoreplacedents(GetEnreplacedyQuery(_index, enreplacedyLogicalName, enreplacedyDoc.PrimaryKey));
				}
			});

			int currentIndex = 0;
			while (currentIndex < enreplacedyIndexDoreplacedents.Length)
			{
				UsingWriter(MethodBase.GetCurrentMethod().Name, false, true, writer =>
				{
					var stopwatch = new Stopwatch();
					stopwatch.Start();

					for (; currentIndex < enreplacedyIndexDoreplacedents.Length; currentIndex++)
					{
						writer.AddDoreplacedent(enreplacedyIndexDoreplacedents[currentIndex].Doreplacedent, enreplacedyIndexDoreplacedents[currentIndex].replacedyzer);

						// We've held onto the write lock too long, there might be other updates waiting on us.
						// Release the lock so they don't time out, then re-enter the queue for the write lock.
						if (stopwatch.Elapsed.TotalSeconds > 10)
						{
							// break;
						}
					}
				});
			}
		}

19 Source : PortalFacetedIndexSearcher.cs
with MIT License
from Adoxio

private IEnumerable<ConstraintHit> BrowseFacetsToConstraintHits(KeyValuePair<string, IFacetAccessible> currentFacet, IEnumerable<FacetConstraints> clientFacetConstraints, BrowseResult browseResults = null)
		{
			var currentFacetConfiguration = this.config.GetConfiguredFacets().FirstOrDefault(configuration => configuration.FieldName == currentFacet.Key);
			if (currentFacetConfiguration == null)
			{
				return Enumerable.Empty<ConstraintHit>();
			}

			var browseFacets = currentFacet.Value.GetFacets();
			////we display the facet either we have non-zero hit count(s) in it, or we have selected ("sticky") facet constraint(s) in it on client side
			var facetsToDisplay = browseFacets.Where(facet => facet.FacetValueHitCount > 0 
				|| clientFacetConstraints.Where(constraints => constraints.FacetName == currentFacet.Key).SelectMany(constraints => constraints.Constraints).Any(constraintName => facet.Value == constraintName));
			if (!facetsToDisplay.Any())
			{
				return Enumerable.Empty<ConstraintHit>();
			}

			var resultConstraintHits = new List<ConstraintHit>();
			IEnumerable<ConstraintHit> currentFacetConstraintHits = Enumerable.Empty<ConstraintHit>();
			switch (currentFacet.Key)
			{
				case FixedFacetsConfiguration.ModifiedDateFacetFieldName:
					currentFacetConstraintHits = browseFacets.Where(facet => facet.Value == "[* TO *]")
							.Concat(browseFacets.Where(facet => facet.Value != "[* TO *]"))
							.Select(browseFacet => new ConstraintHit(browseFacet.Value, browseFacet.FacetValueHitCount, ModifiedOnDateRange.GetRangeDisplayName(browseFacet.Value)));
					break;
				case FixedFacetsConfiguration.RecordTypeFacetFieldName:
					currentFacetConstraintHits = facetsToDisplay.Select(browseFacet => new ConstraintHit(browseFacet.Value, browseFacet.FacetValueHitCount, this.LocalizeRecordTypeName(browseFacet.Value.Split(',')[0])));
					break;
				case FixedFacetsConfiguration.ProductFieldFacetName:
					facetsToDisplay = facetsToDisplay.Where(facet => facet.Value != this.Index.ProductAccessNonKnowledgeArticleDefaultValue && facet.Value != this.Index.ProductAccessDefaultValue);
					if (!facetsToDisplay.Any())
					{
						return Enumerable.Empty<ConstraintHit>();
					}
					currentFacetConstraintHits = facetsToDisplay.Select(browseFacet => new ConstraintHit(browseFacet.Value, browseFacet.FacetValueHitCount, browseFacet.Value));
					break;
				case FixedFacetsConfiguration.RatingFieldFacetName:
					currentFacetConstraintHits = browseFacets.Select(browseFacet => new ConstraintHit(browseFacet.Value, browseFacet.FacetValueHitCount, browseFacet.Value));
					break;
				default:
					currentFacetConstraintHits = facetsToDisplay.Select(browseFacet => new ConstraintHit(browseFacet.Value, browseFacet.FacetValueHitCount, browseFacet.Value));
					break;
			}
			resultConstraintHits.AddRange(currentFacetConstraintHits);
			return resultConstraintHits;
		}

19 Source : PortalFacetedIndexSearcher.cs
with MIT License
from Adoxio

private IEnumerable<ConstraintHit> GroupRecordTypeFacet(KeyValuePair<string, IFacetAccessible> currentFacet, IEnumerable<FacetConstraints> clientFacetConstraints)
		{
			var enreplacedyToRecordMap = new Dictionary<string, string>();
			var groupedFacets = new Dictionary<string, int>();
			var settingsString = this.RecordTypeFacetsEnreplacedies;
			var result = new List<ConstraintHit>();

			settingsString = this.RemoveDuplicates(settingsString);

			if (string.IsNullOrEmpty(settingsString))
			{
				return this.BrowseFacetsToConstraintHits(currentFacet, clientFacetConstraints);
			}

			foreach (var groupName in Web.Mvc.Html.SettingExtensions.SplitSearchFilterOptions(settingsString))
			{
				var trimmedGroupName = groupName.Value.Trim();

				if (string.IsNullOrEmpty(trimmedGroupName))
				{
					continue;
				}

				foreach (var logicalName in trimmedGroupName.Split(','))
				{
					var trimmedLogicalName = logicalName.Trim();

					if (string.IsNullOrEmpty(trimmedLogicalName))
					{
						continue;
					}

					enreplacedyToRecordMap.Add(trimmedLogicalName, trimmedGroupName);
				}

				groupedFacets.Add(trimmedGroupName, 0);
			}

			var browseFacets = currentFacet.Value.GetFacets();
			foreach (var facet in browseFacets)
			{
				var logicalName = facet.Value;

				// adds browseFacet if it's not present in site setting grouping
				if (!enreplacedyToRecordMap.ContainsKey(logicalName))
				{
					groupedFacets.Add(logicalName, facet.FacetValueHitCount);
					continue;
				}

				groupedFacets[enreplacedyToRecordMap[logicalName]] += facet.FacetValueHitCount;
			}

			foreach (var facet in groupedFacets)
			{
				if (facet.Value > 0 || clientFacetConstraints.Where(constraints => constraints.FacetName == currentFacet.Key).SelectMany(constraints => constraints.Constraints).Any(constraintName => facet.Key.Contains(constraintName)))
				{
					result.Add(new ConstraintHit(facet.Key, facet.Value, Web.Extensions.LocalizeRecordTypeName(facet.Key.Split(',')[0])));
				}
			}

			return result.OrderByDescending(x => x.HitCount);
		}

19 Source : SavedQueryIndexer.cs
with MIT License
from Adoxio

public IEnumerable<CrmEnreplacedyIndexDoreplacedent> GetDoreplacedents()
		{
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}", SavedQueryName));

			var doreplacedents = Indexers.SelectMany(indexer => indexer.GetDoreplacedents());

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}", SavedQueryName));

			return doreplacedents;
		}

19 Source : StyleExtensions.cs
with MIT License
from Adoxio

private static IEnumerable<Tuple<string, string, int>> ContentStyles(IPortalViewContext portalViewContext, IEnumerable<EnreplacedyReference> path, IContentMapProvider contentMapProvider)
		{
			var urlProvider = PortalCrmConfigurationManager.CreateDependencyProvider(portalViewContext.PortalName).GetDependency<IContentMapEnreplacedyUrlProvider>();

			if (urlProvider == null)
			{
				return Enumerable.Empty<Tuple<string, string, int>>();
			}

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Getting content styles using Content Map.");

			var cssWebFileNodes = contentMapProvider.Using(map => path.SelectMany((pathItem, pathOffset) =>
			{
				WebPageNode webPage;

				// Guard against null reference exception on webPage.WebFiles. This might happen if WebPage is a translated content, but for whatever reason has no root web page.
				if (!map.TryGetValue(pathItem, out webPage) || webPage.WebFiles == null)
				{
					return Enumerable.Empty<Tuple<int, int, string, string>>();
				}

				return webPage.WebFiles
					.Where(e => e.PartialUrl != null && e.PartialUrl.EndsWith(".css"))
					.Select(e => new Tuple<int, int, string, string>(
						pathOffset,
						e.DisplayOrder.GetValueOrDefault(0),
						urlProvider.GetUrl(map, e),
						e.PartialUrl));
			}));

			return cssWebFileNodes
				.Where(e => !string.IsNullOrEmpty(e.Item3))
				.OrderByDescending(e => e.Item1)
				.ThenBy(e => e.Item2)
				.Select(e => new Tuple<string, string, int>(e.Item3, e.Item4, e.Item1))
				.ToArray();
		}

19 Source : RequestDrop.cs
with MIT License
from Adoxio

private Hash GetParams()
		{
			var @params = new Hash();

			var requestParams = _request.Params;

			if (requestParams != null && requestParams.HasKeys())
			{
				var items = requestParams.AllKeys
					.Where(key => !string.IsNullOrEmpty(key))
					.SelectMany(key => requestParams.GetValues(key) ?? Enumerable.Empty<string>(), (key, values) => new { key, values });

				foreach (var item in items)
				{
					@params[item.key] = item.values;
				}
			}
			
			if (Html.ViewContext != null && Html.ViewContext.ViewData != null)
			{
				@params.Merge(Html.ViewContext.ViewData);
			}

			if (Html.ViewData != null)
			{
				@params.Merge(Html.ViewData);
			}

			return @params;
		}

19 Source : CrmRoleProvider.cs
with MIT License
from Adoxio

public override string[] GetUsersInRole(string roleName)
		{
			if (!RoleExists(roleName))
			{
				return new string[0];
			}

			var context = ServiceContext;

			var roles = GetRolesInWebsiteByName(roleName);

			// If any of the role enreplacedies in question have the Authenticated Users flag switched on, return the names of all users with
			// a non-null username.
			if (_authenticatedUsersRolesEnabled && roles.Any(r => r.GetAttributeValue<bool?>(_attributeMapIsAuthenticatedUsersRole) == true))
			{
				return context.CreateQuery(_userEnreplacedyName)
					.Where(u => u.GetAttributeValue<string>(_attributeMapUsername) != null)
					.Select(u => u.GetAttributeValue<string>(_attributeMapUsername))
					.Distinct().ToArray();
			}

			var usernames = roles.SelectMany(role => role.GetRelatedEnreplacedies(context, _roleToUserRelationshipName).Select(user => user.GetAttributeValue<string>(_attributeMapUsername)));

			return usernames.Distinct().ToArray();
		}

19 Source : SyntaxWalkerBase.cs
with MIT License
from adrianoc

protected void HandleAttributesInMemberDeclaration(IEnumerable<AttributeListSyntax> attributeLists, string varName)
        {
            if (!attributeLists.Any())
                return;

            foreach (var attribute in attributeLists.SelectMany(al => al.Attributes))
            {
                var attrsExp = Context.SemanticModel.GetSymbolInfo(attribute.Name).Symbol.IsDllImportCtor()
                    ? ProcessDllImportAttribute(attribute, varName)
                    : ProcessNormalMethodAttribute(attribute, varName);
                
                AddCecilExpressions(attrsExp);
            }
        }

19 Source : AssemblyComparer.cs
with MIT License
from adrianoc

public bool Compare(IreplacedemblyDiffVisitor visitor)
        {
            if (first.Modules.Count != second.Modules.Count)
            {
                if (!visitor.VisitModules(first, second))
                {
                    return false;
                }
            }

            // We don't handle multi-module replacedemblies. It seems they are very rare in practice
            var sourceModule = first.MainModule;
            var targetModule = second.MainModule;

            var ret = true;
            var firstTypes = new HashSet<TypeDefinition>(sourceModule.Types);

            foreach (var sourceType in firstTypes.SelectMany(t => t.NestedTypes).Concat(firstTypes).Where(t => t.FullName != "<Module>"))
            {
                var targetType = targetModule.Types.SelectMany(ct => ct.NestedTypes).Concat(targetModule.Types).SingleOrDefault(t => t.FullName == sourceType.FullName);

                var typeVisitor = visitor.VisitType(sourceType);
                if (typeVisitor == null)
                {
                    continue;
                }

                if (targetType == null)
                {
                    if (!typeVisitor.VisitMissing(sourceType, targetModule))
                    {
                        return false;
                    }

                    continue;
                }

                if (sourceType.IsNested != targetType.IsNested)
                {
                    throw new Exception("Types differ: " + sourceType.Name + " / " + targetType.Name + " : " + sourceType.IsNested);
                }

                ret = ret && CheckTypeCustomAttributes(typeVisitor, sourceType, targetType);
                ret = ret && CheckTypeAttributes(typeVisitor, sourceType, targetType);
                ret = ret && CheckTypeGenericInformation(typeVisitor, sourceType, targetType);
                ret = ret && CheckTypeMembers(typeVisitor, sourceType, targetType);
                ret = ret && CheckTypeInheritance(typeVisitor, sourceType, targetType);
                ret = ret && CheckImplementedInterfaces(typeVisitor, sourceType, targetType);
            }

            //TODO: Check missing clreplacedes
            return ret;
        }

19 Source : BlockParser.cs
with GNU General Public License v3.0
from Aekras1a

private static void LinkBlocks(List<BasicBlock<CILInstrList>> blocks)
        {
            var instrMap = blocks
                .SelectMany(block => block.Content.Select(instr => new {Instr = instr, Block = block}))
                .ToDictionary(instr => instr.Instr, instr => instr.Block);

            foreach(var block in blocks)
            foreach(var instr in block.Content)
                if(instr.Operand is Instruction)
                {
                    var dstBlock = instrMap[(Instruction) instr.Operand];
                    dstBlock.Sources.Add(block);
                    block.Targets.Add(dstBlock);
                }
                else if(instr.Operand is Instruction[])
                {
                    foreach(var target in (Instruction[]) instr.Operand)
                    {
                        var dstBlock = instrMap[target];
                        dstBlock.Sources.Add(block);
                        block.Targets.Add(dstBlock);
                    }
                }
            for(var i = 0; i < blocks.Count; i++)
            {
                var footer = blocks[i].Content.Last();
                if(footer.OpCode.FlowControl != FlowControl.Branch &&
                   footer.OpCode.FlowControl != FlowControl.Return &&
                   footer.OpCode.FlowControl != FlowControl.Throw &&
                   i + 1 < blocks.Count)
                {
                    var src = blocks[i];
                    var dst = blocks[i + 1];
                    if(!src.Targets.Contains(dst))
                    {
                        src.Targets.Add(dst);
                        dst.Sources.Add(src);
                        src.Content.Add(Instruction.Create(OpCodes.Br, dst.Content[0]));
                    }
                }
            }
        }

19 Source : ConflictingTransactionIdentificationService.cs
with MIT License
from AElfProject

private List<ExecutionReturnSet> FindPossibleConflictingReturnSets(List<ExecutionReturnSet> returnSets,
            List<ExecutionReturnSet> conflictingSets)
        {
            var existingKeys = new HashSet<string>(returnSets.SelectMany(rs => rs.StateAccesses.Keys));
            var possibleConflictingKeys = new HashSet<string>(conflictingSets.SelectMany(rs => rs.StateAccesses.Keys));
            possibleConflictingKeys.IntersectWith(existingKeys);
            return returnSets.Concat(conflictingSets)
                .Where(rs => rs.StateAccesses.Any(a => possibleConflictingKeys.Contains(a.Key))).ToList();
        }

19 Source : TransactionWithResourceInfoExtensions.cs
with MIT License
from AElfProject

public static HashSet<ScopedStatePath> GetReadOnlyPaths(
            this List<TransactionWithResourceInfo> transactionWithResourceInfos)
        {
            var readPaths =
                new HashSet<ScopedStatePath>(transactionWithResourceInfos.SelectMany(r => r.TransactionResourceInfo.ReadPaths));
            var writePaths =
                new HashSet<ScopedStatePath>(transactionWithResourceInfos.SelectMany(r => r.TransactionResourceInfo.WritePaths));
            readPaths.ExceptWith(writePaths);
            return readPaths;
        }

19 Source : FixAllContextHelper.cs
with Apache License 2.0
from agoda-com

public static async Task<ImmutableDictionary<Doreplacedent, ImmutableArray<Diagnostic>>> GetDoreplacedentDiagnosticsToFixAsync(FixAllContext fixAllContext)
        {
            var allDiagnostics = ImmutableArray<Diagnostic>.Empty;
            var projectsToFix = ImmutableArray<Project>.Empty;

            var doreplacedent = fixAllContext.Doreplacedent;
            var project = fixAllContext.Project;

            switch (fixAllContext.Scope)
            {
                case FixAllScope.Doreplacedent:
                    if (doreplacedent != null)
                    {
                        var doreplacedentDiagnostics = await fixAllContext.GetDoreplacedentDiagnosticsAsync(doreplacedent).ConfigureAwait(false);
                        return ImmutableDictionary<Doreplacedent, ImmutableArray<Diagnostic>>.Empty.Sereplacedem(doreplacedent, doreplacedentDiagnostics);
                    }

                    break;

                case FixAllScope.Project:
                    projectsToFix = ImmutableArray.Create(project);
                    allDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, project).ConfigureAwait(false);
                    break;

                case FixAllScope.Solution:
                    projectsToFix = project.Solution.Projects
                        .Where(p => p.Language == project.Language)
                        .ToImmutableArray();

                    var diagnostics = new ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>>();
                    var tasks = new Task[projectsToFix.Length];
                    for (var i = 0; i < projectsToFix.Length; i++)
                    {
                        fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                        var projectToFix = projectsToFix[i];
                        tasks[i] = Task.Run(
                            async () =>
                            {
                                var projectDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, projectToFix).ConfigureAwait(false);
                                diagnostics.TryAdd(projectToFix.Id, projectDiagnostics);
                            }, fixAllContext.CancellationToken);
                    }

                    await Task.WhenAll(tasks).ConfigureAwait(false);
                    allDiagnostics = allDiagnostics.AddRange(diagnostics.SelectMany(i => i.Value.Where(x => fixAllContext.DiagnosticIds.Contains(x.Id))));
                    break;
            }

            if (allDiagnostics.IsEmpty)
            {
                return ImmutableDictionary<Doreplacedent, ImmutableArray<Diagnostic>>.Empty;
            }

            return await GetDoreplacedentDiagnosticsToFixAsync(allDiagnostics, projectsToFix, fixAllContext.CancellationToken).ConfigureAwait(false);
        }

19 Source : ServiceCollectionExtensions.cs
with MIT License
from ai-traders

public static void AddCarter(this IServiceCollection services)
        {
            //PATCH around same issues as in https://github.com/CarterCommunity/Carter/pull/88
            // we rather just explicitly state replacedembly with modules to fix loading issues.
            var replacedemblies = new [] { typeof(IndexModule).replacedembly };

            CarterDiagnostics diagnostics = new CarterDiagnostics();
            services.AddSingleton(diagnostics);

            var validators = replacedemblies.SelectMany(replaced => replaced.GetTypes())
                .Where(typeof(IValidator).IsreplacedignableFrom)
                .Where(t => !t.GetTypeInfo().IsAbstract);

            foreach (var validator in validators)
            {
                diagnostics.AddValidator(validator);
                services.AddSingleton(typeof(IValidator), validator);
            }

            services.AddSingleton<IValidatorLocator, DefaultValidatorLocator>();

            services.AddRouting();

            var modules = replacedemblies.SelectMany(x => x.GetTypes()
                .Where(t =>
                    !t.IsAbstract &&
                    typeof(CarterModule).IsreplacedignableFrom(t) &&
                    t != typeof(CarterModule) &&
                    t.IsPublic
                ));

            foreach (var module in modules)
            {
                diagnostics.AddModule(module);
                services.AddScoped(module);
                services.AddScoped(typeof(CarterModule), module);
            }

            var schs = replacedemblies.SelectMany(x => x.GetTypes().Where(t => typeof(IStatusCodeHandler).IsreplacedignableFrom(t) && t != typeof(IStatusCodeHandler)));
            foreach (var sch in schs)
            {
                diagnostics.AddStatusCodeHandler(sch);
                services.AddScoped(typeof(IStatusCodeHandler), sch);
            }

            var responseNegotiators = replacedemblies.SelectMany(x => x.GetTypes()
                .Where(t =>
                    !t.IsAbstract &&
                    typeof(IResponseNegotiator).IsreplacedignableFrom(t) &&
                    t != typeof(IResponseNegotiator) &&
                    t != typeof(DefaultJsonResponseNegotiator)
                ));

            foreach (var negotiatator in responseNegotiators)
            {
                diagnostics.AddResponseNegotiator(negotiatator);
                services.AddSingleton(typeof(IResponseNegotiator), negotiatator);
            }

            services.AddSingleton<IResponseNegotiator, DefaultJsonResponseNegotiator>();
        }

19 Source : StargateMemory.cs
with MIT License
from AiursoftWeb

public (int channelsCount, int totalMessages) GetMonitoringReport()
        {
            return (Channels.Count, Channels
                .SelectMany(t => t.Value.Messages)
                .Count());
        }

19 Source : Extensions.cs
with MIT License
from akaskela

public static IEnumerable<U> Children<T, U>(this IEnumerable<T> source) where T : JToken
        {
            ValidationUtils.ArgumentNotNull(source, nameof(source));

            return source.SelectMany(c => c.Children()).Convert<JToken, U>();
        }

19 Source : Extensions.cs
with MIT License
from akaskela

public static IJEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken
        {
            ValidationUtils.ArgumentNotNull(source, nameof(source));

            return source.SelectMany(j => j.Ancestors()).AsJEnumerable();
        }

19 Source : Extensions.cs
with MIT License
from akaskela

public static IJEnumerable<JToken> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JToken
        {
            ValidationUtils.ArgumentNotNull(source, nameof(source));

            return source.SelectMany(j => j.AncestorsAndSelf()).AsJEnumerable();
        }

19 Source : Extensions.cs
with MIT License
from akaskela

public static IJEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer
        {
            ValidationUtils.ArgumentNotNull(source, nameof(source));

            return source.SelectMany(j => j.Descendants()).AsJEnumerable();
        }

19 Source : Extensions.cs
with MIT License
from akaskela

public static IJEnumerable<JToken> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer
        {
            ValidationUtils.ArgumentNotNull(source, nameof(source));

            return source.SelectMany(j => j.DescendantsAndSelf()).AsJEnumerable();
        }

19 Source : Extensions.cs
with MIT License
from akaskela

public static IJEnumerable<JProperty> Properties(this IEnumerable<JObject> source)
        {
            ValidationUtils.ArgumentNotNull(source, nameof(source));

            return source.SelectMany(d => d.Properties()).AsJEnumerable();
        }

19 Source : DefaultContractResolver.cs
with MIT License
from akaskela

private MemberInfo GetExtensionDataMemberForType(Type type)
        {
            IEnumerable<MemberInfo> members = GetClreplacedHierarchyForType(type).SelectMany(baseType =>
            {
                IList<MemberInfo> m = new List<MemberInfo>();
                m.AddRange(baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
                m.AddRange(baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));

                return m;
            });

            MemberInfo extensionDataMember = members.LastOrDefault(m =>
            {
                MemberTypes memberType = m.MemberType();
                if (memberType != MemberTypes.Property && memberType != MemberTypes.Field)
                {
                    return false;
                }

                // last instance of attribute wins on type if there are multiple
                if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false))
                {
                    return false;
                }

                if (!ReflectionUtils.CanReadMemberValue(m, true))
                {
                    throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
                }

                Type t = ReflectionUtils.GetMemberUnderlyingType(m);

                Type dictionaryType;
                if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType))
                {
                    Type keyType = dictionaryType.GetGenericArguments()[0];
                    Type valueType = dictionaryType.GetGenericArguments()[1];

                    if (keyType.IsreplacedignableFrom(typeof(string)) && valueType.IsreplacedignableFrom(typeof(JToken)))
                    {
                        return true;
                    }
                }

                throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary<string, JToken>.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
            });

            return extensionDataMember;
        }

19 Source : ValidatorBehavior.cs
with MIT License
from AleksandreJavakhishvili

public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            var failures = _validators
                .Select(v => v.Validate(request))
                .SelectMany(result => result.Errors)
                .Where(error => error != null)
                .ToList();

            if (failures.Any())
            {
                throw new CommandValidatorException(
                    $"Command Validation Errors for type {typeof(TRequest).Name}", new ValidationException("Validation exception", failures));
            }

            var response = await next();
            return response;
        }

19 Source : KFixedTableRouter.cs
with MIT License
from alethic

ValueTask<IEnumerable<KNodeEndpointInfo<TNodeId>>> SelectAsyncIter(in TNodeId key, int k, CancellationToken cancellationToken = default)
        {
            if (k == 0)
                return GetBucket(key).SelectAsync(key, cancellationToken);

            // take first bucket; then append others; pretty inefficient
            var c = new KNodeIdDistanceComparer<TNodeId>(key);
            var f = key.Equals(host.SelfId) ? null : buckets[GetBucketIndex(host.SelfId, key)];
            var s = f == null ? Enumerable.Empty<KBucket<TNodeId>>() : new[] { f };
            var l = s.Concat(buckets.Except(s)).SelectMany(i => i).OrderBy(i => i.NodeId, c).Take(k).Select(i => new KNodeEndpointInfo<TNodeId>(i.NodeId, i.Endpoints));
            return new ValueTask<IEnumerable<KNodeEndpointInfo<TNodeId>>>(l);
        }

19 Source : KFixedTableRouter.cs
with MIT License
from alethic

public IEnumerator<KNodeEndpointInfo<TNodeId>> GetEnumerator()
        {
            return buckets.SelectMany(i => i).Select(i => new KNodeEndpointInfo<TNodeId>(i.NodeId, i.Endpoints)).GetEnumerator();
        }

19 Source : DnsClientBase.cs
with Apache License 2.0
from alexreinert

private List<DnsClientEndpointInfo> GetEndpointInfos()
		{
			List<DnsClientEndpointInfo> endpointInfos;
			if (_isAnyServerMulticast)
			{
				var localIPs = NetworkInterface.GetAllNetworkInterfaces()
					.Where(n => n.SupportsMulticast && (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback))
					.SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(a => a.Address))
					.Where(a => !IPAddress.IsLoopback(a) && ((a.AddressFamily == AddressFamily.InterNetwork) || a.IsIPv6LinkLocal))
					.ToList();

				endpointInfos = _servers
					.SelectMany(
						s =>
						{
							if (s.IsMulticast())
							{
								return localIPs
									.Where(l => l.AddressFamily == s.AddressFamily)
									.Select(
										l => new DnsClientEndpointInfo
										{
											IsMulticast = true,
											ServerAddress = s,
											LocalAddress = l
										});
							}
							else
							{
								return new[]
								{
									new DnsClientEndpointInfo
									{
										IsMulticast = false,
										ServerAddress = s,
										LocalAddress = s.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any
									}
								};
							}
						}).ToList();
			}
			else
			{
				endpointInfos = _servers
					.Where(x => IsIPv6Enabled || (x.AddressFamily == AddressFamily.InterNetwork))
					.Select(
						s => new DnsClientEndpointInfo
						{
							IsMulticast = false,
							ServerAddress = s,
							LocalAddress = s.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any
						}
					).ToList();
			}
			return endpointInfos;
		}

19 Source : InspectorEditor.cs
with Apache License 2.0
from Algoryx

private bool IsTargetMostProbablyDeleted()
    {
      // Nothing selected so the user probably hit 'Delete'.
      if ( Selection.activeGameObject == null || m_targetGameObjects == null )
        return true;

      // Any of the previously (OnEnable) collected game objects
      // is "null".
      if ( m_targetGameObjects.Any( go => go == null ) )
        return true;

      var targetComponents = m_targetGameObjects.SelectMany( go => go.GetComponents( m_targetType ) )
                                                .Select( component => component ).ToArray();
      // Current number of components doesn't match the amount of
      // components collected in OnEnable.
      return targetComponents.Length != m_numTargetGameObjectsTargetComponents;
    }

19 Source : DocumentHelper.cs
with MIT License
from aliencube

public Dictionary<string, OpenApiSchema> GetOpenApiSchemas(List<MethodInfo> elements, NamingStrategy namingStrategy, VisitorCollection collection)
        {
            var requests = elements.SelectMany(p => p.GetCustomAttributes<OpenApiRequestBodyAttribute>(inherit: false))
                                   .Select(p => p.BodyType);
            var responses = elements.SelectMany(p => p.GetCustomAttributes<OpenApiResponseWithBodyAttribute>(inherit: false))
                                    .Select(p => p.BodyType);
            var types = requests.Union(responses)
                                .Select(p => p.IsOpenApiArray() || p.IsOpenApiDictionary() ? p.GetOpenApiSubType() : p)
                                .Distinct()
                                .Where(p => !p.IsSimpleType())
                                .Where(p => p != typeof(JObject))
                                .Where(p => p != typeof(JToken))
                                .Where(p => !typeof(Array).IsreplacedignableFrom(p))
                                .ToList();

            var rootSchemas = new Dictionary<string, OpenApiSchema>();
            var schemas = new Dictionary<string, OpenApiSchema>();

            this._acceptor.Types = types.ToDictionary(p => p.GetOpenApiTypeName(namingStrategy), p => p);
            this._acceptor.RootSchemas = rootSchemas;
            this._acceptor.Schemas = schemas;

            this._acceptor.Accept(collection, namingStrategy);

            var union = schemas.Concat(rootSchemas.Where(p => !schemas.Keys.Contains(p.Key)))
                               .Distinct()
                               .OrderBy(p => p.Key)
                               .ToDictionary(p => p.Key,
                                             p =>
                                             {
                                                 // replacedle was intentionally added for schema key.
                                                 // It's not necessary when it's added to the root schema.
                                                 // Therefore, it's removed.
                                                 p.Value.replacedle = null;
                                                 return p.Value;
                                             });

            return union;
        }

19 Source : CommonExtensions.cs
with MIT License
from aliyun

internal static IEnumerable<KeyValuePair<String, String>> ToEnumerable(this NameValueCollection source)
        {
            return source.AllKeys
                .SelectMany(key => source.GetValues(key), (key, value) => new KeyValuePair<String, String>(key, value));
        }

19 Source : IntegrationTests.cs
with Apache License 2.0
from allure-framework

private void ParseFeatures(string featuresDir)
    {
      var parser = new Parser();
      var scenarios = new List<Scenario>();
      var features = new DirectoryInfo(featuresDir).GetFiles("*.feature");
      scenarios.AddRange(features.SelectMany(f =>
      {
        var children = parser.Parse(f.FullName).Feature.Children.ToList();
        var scenarioOutlines = children.Where(x => (x as dynamic).Examples.Length > 0).ToList();
        foreach (var s in scenarioOutlines)
        {
          var examplesCount = ((s as dynamic).Examples as dynamic)[0].TableBody.Length;
          for (int i = 1; i < examplesCount; i++)
          {
            children.Add(s);
          }
        }
        return children;
      })
          .Select(x => x as Scenario));

      scenariosByStatus =
          scenarios.GroupBy(x => x.Tags.FirstOrDefault(x =>
                                         Enum.GetNames(typeof(Status)).Contains(x.Name.Replace("@", "")))?.Name
                                     .Replace("@", "") ??
                                 "_notag_", x => x.Name);
    }

See More Examples