Example #1
0
 protected ReadWriteAggregator(IImmutableSet <Address> nodes, IImmutableSet <Address> unreachable, TimeSpan timeout)
 {
     Timeout     = timeout;
     Nodes       = nodes;
     Unreachable = unreachable;
     Reachable   = nodes.Except(unreachable);
     Remaining   = Nodes;
     _sendToSecondarySchedule  = Context.System.Scheduler.ScheduleTellOnceCancelable((int)Timeout.TotalMilliseconds / 5, Self, SendToSecondary.Instance, Self);
     _timeoutSchedule          = Context.System.Scheduler.ScheduleTellOnceCancelable(Timeout, Self, ReceiveTimeout.Instance, Self);
     _primaryAndSecondaryNodes = new Lazy <Tuple <IImmutableSet <Address>, IImmutableSet <Address> > >(() =>
     {
         var primarySize = Nodes.Count - DoneWhenRemainingSize;
         if (primarySize >= nodes.Count)
         {
             return(Tuple.Create(nodes, (IImmutableSet <Address>)ImmutableHashSet <Address> .Empty));
         }
         else
         {
             var n = Nodes.OrderBy(x => ThreadLocalRandom.Current.Next()).ToArray();
             var p = n.Take(primarySize).ToImmutableHashSet();
             var s = n.Skip(primarySize).Take(MaxSecondaryNodes).ToImmutableHashSet();
             return(Tuple.Create((IImmutableSet <Address>)p, (IImmutableSet <Address>)s));
         }
     });
 }
Example #2
0
        public static DiffSetResult <T> DiffWith <T>(this IImmutableSet <T> current, IImmutableSet <T> previous, IEqualityComparer <T> equalityComparer = null)
        {
            var comparer = equalityComparer ?? EqualityComparer <T> .Default;

            return(new DiffSetResult <T>(
                       current.Except(previous, comparer).ToImmutableHashSet(),
                       previous.Except(current, comparer).ToImmutableHashSet(),
                       current));
        }
        public void TestExcept()
        {
            IImmutableSet <int> set = CreateSet <int>();

            Assert.Throws <ArgumentNullException>(() => set.Except(null));

            // Return without iterating if the set is already empty
            Assert.Same(set, set.Except(EverythingThrowsEnumerable <int> .Instance));

            // Test ExceptWith self
            set = set.Add(1);
            set = set.Except(TransformEnumerableForSetOperation(set));
            Assert.Empty(set);

            // Test ExceptWith subset
            set = set.Union(TransformEnumerableForSetOperation(Enumerable.Range(0, 10)));
            set = set.Except(TransformEnumerableForSetOperation(new[] { 1, 3, 5, 7, 9 }));
            Assert.Equal(new[] { 0, 2, 4, 6, 8 }, set);
            set = set.Except(TransformEnumerableForSetOperation(new[] { 0, 2, 4, 6, 8 }));
            Assert.Empty(set);
        }
Example #4
0
        private void ExceptTestHelper <T>(IImmutableSet <T> set, params T[] valuesToRemove)
        {
            Contract.Requires(set != null);
            Contract.Requires(valuesToRemove != null);

            var expectedSet = new HashSet <T>(set);

            expectedSet.ExceptWith(valuesToRemove);

            var actualSet = set.Except(valuesToRemove);

            CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
        }
Example #5
0
        private void ExceptTestHelper <T>(IImmutableSet <T> set, params T[] valuesToRemove)
        {
            Assert.NotNull(set);
            Assert.NotNull(valuesToRemove);

            var expectedSet = new HashSet <T>(set);

            expectedSet.ExceptWith(valuesToRemove);

            var actualSet = set.Except(valuesToRemove);

            CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());

            this.VerifyAvlTreeState(actualSet);
        }
Example #6
0
        private void RemoveTestHelper <T>(IImmutableSet <T> set, params T[] values)
        {
            Contract.Requires(set != null);
            Contract.Requires(values != null);

            Assert.Same(set, set.Except(Enumerable.Empty <T>()));

            int initialCount = set.Count;
            int removedCount = 0;

            foreach (T value in values)
            {
                var nextSet = set.Remove(value);
                Assert.NotSame(set, nextSet);
                Assert.Equal(initialCount - removedCount, set.Count);
                Assert.Equal(initialCount - removedCount - 1, nextSet.Count);

                Assert.Same(nextSet, nextSet.Remove(value)); //, "Removing a non-existing element should not change the set reference.");
                removedCount++;
                set = nextSet;
            }

            Assert.Equal(initialCount - removedCount, set.Count);
        }
Example #7
0
 public static IImmutableSet <T> difference <T>(IImmutableSet <T> setA, IImmutableSet <T> setB) =>
 setA.Except(setB);
Example #8
0
        public async Task <CommandResult> Pokedex(CommandContext context)
        {
            (Optional <User> optionalUser, Optional <string> optionalMode, Optional <User> optionalCompareUser) =
                await context.ParseArgs <Optional <User>, Optional <string>, Optional <User> >();

            User user   = optionalUser.OrElse(context.Message.User);
            bool isSelf = user == context.Message.User;

            if (!optionalMode.IsPresent)
            {
                int numUniqueSpecies = (await _badgeRepo.CountByUserPerSpecies(user.Id)).Count;
                return(new CommandResult
                {
                    Response = isSelf
                        ? $"You have collected {numUniqueSpecies} distinct Pokémon badge(s)"
                        : $"{user.Name} has collected {numUniqueSpecies} distinct Pokémon badge(s)"
                });
            }

            string mode = optionalMode.Value;
            ImmutableSortedDictionary <PkmnSpecies, int> numBadgesPerSpecies =
                await _badgeRepo.CountByUserPerSpecies(user.Id);

            if (mode.Equals(PokedexModeMissing))
            {
                IEnumerable <PkmnSpecies> missingList     = _knownSpecies.Except(numBadgesPerSpecies.Keys);
                IEnumerable <string>      badgesFormatted = missingList.Select(entry => $"{entry}");
                return(new CommandResult
                {
                    Response = isSelf
                        ? $"You are currently missing the following badge(s): {string.Join(", ", badgesFormatted)}"
                        : $"{user.Name} is currently missing the following badge(s): {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (mode.Equals(PokedexModeDupes))
            {
                var dupeList = numBadgesPerSpecies.Where(kvp => kvp.Value > 1).ToList();
                if (!dupeList.Any())
                {
                    return(new CommandResult
                    {
                        Response = isSelf
                            ? $"You do not own any duplicate Pokémon badges"
                            : $"{user.Name} does not own any duplicate Pokémon badges"
                    });
                }
                IEnumerable <string> badgesFormatted = dupeList.Select(kvp => $"{kvp.Key}");
                return(new CommandResult
                {
                    Response = isSelf
                        ? $"You are owning duplicates of the following badge(s): {string.Join(", ", badgesFormatted)}"
                        : $"{user.Name} owns duplicates of the following badge(s): {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (mode.Equals(PokedexModeComplementFromDupes))
            {
                if (!optionalCompareUser.IsPresent)
                {
                    return(new CommandResult
                    {
                        Response = $"Mode {PokedexModeComplementFromDupes} requires a second user argument"
                    });
                }
                ImmutableSortedDictionary <PkmnSpecies, int> compareUser =
                    await _badgeRepo.CountByUserPerSpecies(optionalCompareUser.Value.Id);

                var compareUserDupeList = compareUser.Where(kvp => kvp.Value > 1).Select(kvp => kvp.Key);

                var differenceList = compareUserDupeList.Except(numBadgesPerSpecies.Keys).ToList();
                if (!differenceList.Any())
                {
                    return(new CommandResult
                    {
                        Response = $"{optionalCompareUser.Value.Name} does not own any duplicate Pokémon badges {user.Name} is missing"
                    });
                }
                IEnumerable <string> badgesFormatted = differenceList.Select(entry => $"{entry}");
                return(new CommandResult
                {
                    Response = $"{optionalCompareUser.Value.Name} owns the following duplicate badge(s) {user.Name} is missing: {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (mode.Equals(PokedexModeComplementFrom))
            {
                if (!optionalCompareUser.IsPresent)
                {
                    return(new CommandResult
                    {
                        Response = $"Mode {PokedexModeComplementFrom} requires a second user argument"
                    });
                }
                ImmutableSortedDictionary <PkmnSpecies, int> compareUser =
                    await _badgeRepo.CountByUserPerSpecies(optionalCompareUser.Value.Id);

                var differenceList = compareUser.Keys.Except(numBadgesPerSpecies.Keys).ToList();
                if (!differenceList.Any())
                {
                    return(new CommandResult
                    {
                        Response = $"{optionalCompareUser.Value.Name} does not own any Pokémon badges {user.Name} is missing"
                    });
                }
                IEnumerable <string> badgesFormatted = differenceList.Select(entry => $"{entry}");
                return(new CommandResult
                {
                    Response = $"{optionalCompareUser.Value.Name} owns the following badge(s) {user.Name} is missing: {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (mode.Equals(PokedexModeModes))
            {
                return(new CommandResult
                {
                    Response = $"Supported modes are '{PokedexModeDupes}': Show duplicate badges, '{PokedexModeMissing}': Show missing badges, "
                               + $"'{PokedexModeComplementFrom}' Compares missing badges from User A with owned badges from User B, "
                               + $"'{PokedexModeComplementFromDupes}' Compares missing badges from User A with owned duplicate badges from User B"
                });
            }
            return(new CommandResult
            {
                Response = $"Unsupported mode '{mode}'. Current modes supported: {PokedexModeModes}, {PokedexModeDupes}, {PokedexModeMissing}, {PokedexModeComplementFromDupes}, {PokedexModeComplementFrom}"
            });
        }
Example #9
0
 /// <summary>
 /// Removes entries matching <paramref name="entry"/> and <paramref name="timestamps"/> and returns updated <see cref="OrSet{T}"/>.
 /// </summary>
 public OrSet <T> Remove(T entry, IImmutableSet <VectorTime> timestamps)
 {
     return(new OrSet <T>(versionedEntries.Except(timestamps.Select(t => new Versioned <T>(entry, t)))));
 }
Example #10
0
        private IEnumerable <string> VerifyPropertyMap <TTo>(IImmutableSet <string> target,
                                                             IImmutableSet <string> sourceMapped,
                                                             IImmutableSet <string> unverifiedSourceMapped,
                                                             ImmutableQueue <Tuple <PropertyInfo, MapsToAttribute> > pendingVerifications)
        {
            var targetMapped = new HashSet <string>();

            //Wrap up any pending verifications first
            foreach (var map in pendingVerifications)
            {
                var targetPropertyName = map.Item2.PropertyName;
                if (target.Contains(targetPropertyName))
                {
                    var targetProperty = typeof(TTo).GetProperty(targetPropertyName);
                    if (targetProperty == null)
                    {
                        yield return(CreateReadableMapFailure(FailureReason.SourcePropertyIsNotMapped, map.Item1));
                    }

                    if (targetProperty.SetMethod == null || !targetProperty.SetMethod.IsPublic)
                    {
                        yield return(CreateReadableMapFailure(FailureReason.TargetPropertyDoesNotHaveSet, map.Item1, targetProperty));
                    }

                    if (targetMapped.Contains(targetPropertyName))
                    {
                        yield return(CreateReadableMapFailure(FailureReason.TargetPropertyHasMultipleSources, targetProperty));
                    }

                    //TODO: Verify type compatibility

                    sourceMapped = sourceMapped.Add(map.Item1.Name);
                    targetMapped.Add(targetPropertyName);
                }
                else
                {
                    yield return(CreateReadableMapFailure(FailureReason.SourcePropertyIsNotMapped, map.Item1));
                }
            }

            //Resolve the implicit mappings
            var missingExpectedTargetProperties = target.Except(targetMapped).Except(unverifiedSourceMapped);
            var missingExpectedSourceProperties = unverifiedSourceMapped.Except(target);

            foreach (var name in missingExpectedTargetProperties)
            {
                var targetProperty = typeof(TTo).GetProperty(name);
                yield return(CreateReadableMapFailure(FailureReason.TargetPropertyIsNotMapped, targetProperty));
            }

            foreach (var name in missingExpectedSourceProperties)
            {
                var sourceProperty = typeof(TFrom).GetProperty(name);
                yield return(CreateReadableMapFailure(FailureReason.SourcePropertyIsNotMapped, sourceProperty));
            }

            var solidifiedMappings = unverifiedSourceMapped.Intersect(target);

            foreach (var name in solidifiedMappings)
            {
                //We could potentially have a mapping collision if someone already explicitly mapped a property
                //to one that was already being mapped, so make sure that's not the case.
                if (targetMapped.Contains(name))
                {
                    var targetProperty = typeof(TTo).GetProperty(name);
                    yield return(CreateReadableMapFailure(FailureReason.TargetPropertyHasMultipleSources, targetProperty));
                }
                else
                {
                    var targetProperty = typeof(TTo).GetProperty(name);
                    if (targetProperty.SetMethod == null || !targetProperty.SetMethod.IsPublic)
                    {
                        yield return(CreateReadableMapFailure(FailureReason.TargetPropertyDoesNotHaveSet, targetProperty));
                    }

                    targetMapped.Add(name);
                }
            }
        }
Example #11
0
 public IImmutableSet <T> Except(IEnumerable <T> other) =>
 _set.Except(other).ToStructural().Optimize("With Aggregate, tracking hashCode changes like Add.");
Example #12
0
 public ElementSet Except(IEnumerable <Element> other)
 {
     return(new ElementSet(_immutableSetImplementation.Except(other)));
 }
 public static IImmutableSet <T> RemoveDefault <T>(this IImmutableSet <T> set)
 {
     return(set.Except(DefaultSet <T> .Instance));
 }
 public static bool ContainsDefault <T>(this IImmutableSet <T> set)
 {
     return(set.Except(DefaultSet <T> .Instance).Count < set.Count);
 }
        /// <summary>
        /// Deletes items from the project, and optionally from disk.
        /// Note: Delete and Remove commands are handled via IVsHierarchyDeleteHandler3, not by
        /// IAsyncCommandGroupHandler and first asks us we CanRemove nodes. If yes then RemoveAsync is called.
        /// We can remove only nodes that are standard and based on project items, i.e. nodes that
        /// are created by default IProjectDependenciesSubTreeProvider implementations and have
        /// DependencyNode.GenericDependencyFlags flags and IRule with Context != null, in order to obtain
        /// node's itemSpec. ItemSpec then used to remove a project item having same Include.
        /// </summary>
        /// <param name="nodes">The nodes that should be deleted.</param>
        /// <param name="deleteOptions">A value indicating whether the items should be deleted from disk as well as
        /// from the project file.
        /// </param>
        /// <exception cref="InvalidOperationException">Thrown when <see cref="IProjectTreeProvider.CanRemove"/>
        /// would return <c>false</c> for this operation.</exception>
        public override async Task RemoveAsync(IImmutableSet <IProjectTree> nodes,
                                               DeleteOptions deleteOptions = DeleteOptions.None)
        {
            if (deleteOptions.HasFlag(DeleteOptions.DeleteFromStorage))
            {
                throw new NotSupportedException();
            }

            // Get the list of shared import nodes.
            IEnumerable <IProjectTree> sharedImportNodes = nodes.Where(node =>
                                                                       node.Flags.Contains(ProjectTreeFlags.Common.SharedProjectImportReference));

            // Get the list of normal reference Item Nodes (this excludes any shared import nodes).
            IEnumerable <IProjectTree> referenceItemNodes = nodes.Except(sharedImportNodes);

            using (var access = await ProjectLockService.WriteLockAsync())
            {
                var project = await access.GetProjectAsync(ActiveConfiguredProject).ConfigureAwait(true);

                // Handle the removal of normal reference Item Nodes (this excludes any shared import nodes).
                foreach (var node in referenceItemNodes)
                {
                    if (node.BrowseObjectProperties == null || node.BrowseObjectProperties.Context == null)
                    {
                        // if node does not have an IRule with valid ProjectPropertiesContext we can not
                        // get it's itemsSpec. If nodes provided by custom IProjectDependenciesSubTreeProvider
                        // implementation, and have some custom IRule without context, it is not a problem,
                        // since they wouldnot have DependencyNode.GenericDependencyFlags and we would not
                        // end up here, since CanRemove would return false and Remove command would not show
                        // up for those nodes.
                        continue;
                    }

                    var nodeItemContext         = node.BrowseObjectProperties.Context;
                    var unresolvedReferenceItem = project.GetItemsByEvaluatedInclude(nodeItemContext.ItemName)
                                                  .FirstOrDefault(item => string.Equals(item.ItemType,
                                                                                        nodeItemContext.ItemType,
                                                                                        StringComparison.OrdinalIgnoreCase));

                    Report.IfNot(unresolvedReferenceItem != null, "Cannot find reference to remove.");
                    if (unresolvedReferenceItem != null)
                    {
                        await access.CheckoutAsync(unresolvedReferenceItem.Xml.ContainingProject.FullPath)
                        .ConfigureAwait(true);

                        project.RemoveItem(unresolvedReferenceItem);
                    }
                }

                // Handle the removal of shared import nodes.
                var projectXml = await access.GetProjectXmlAsync(UnconfiguredProject.FullPath)
                                 .ConfigureAwait(true);

                foreach (var sharedImportNode in sharedImportNodes)
                {
                    // Find the import that is included in the evaluation of the specified ConfiguredProject that
                    // imports the project file whose full path matches the specified one.
                    var matchingImports = from import in project.Imports
                                          where import.ImportingElement.ContainingProject == projectXml
                                          where PathHelper.IsSamePath(import.ImportedProject.FullPath,
                                                                      sharedImportNode.FilePath)
                                          select import;
                    foreach (var importToRemove in matchingImports)
                    {
                        var importingElementToRemove = importToRemove.ImportingElement;
                        Report.IfNot(importingElementToRemove != null,
                                     "Cannot find shared project reference to remove.");
                        if (importingElementToRemove != null)
                        {
                            await access.CheckoutAsync(importingElementToRemove.ContainingProject.FullPath)
                            .ConfigureAwait(true);

                            importingElementToRemove.Parent.RemoveChild(importingElementToRemove);
                        }
                    }
                }
            }
        }
 public static IImmutableSet <T> RemoveAll <T>(this IImmutableSet <T> set, Func <T, bool> predicate)
 {
     return(set.Except(set.Where(predicate)));
 }
        public async Task <CommandResult> Pokedex(CommandContext context)
        {
            (Optional <User> optionalUser, Optional <string> optionalMode, Optional <User> optionalCompareUser) =
                await context.ParseArgs <Optional <User>, Optional <string>, Optional <User> >();

            User user   = optionalUser.OrElse(context.Message.User);
            bool isSelf = user == context.Message.User;

            if (!optionalMode.IsPresent)
            {
                int numUniqueSpecies = (await _badgeRepo.CountByUserPerSpecies(user.Id)).Count;
                return(new CommandResult
                {
                    Response = isSelf
                        ? $"You have collected {numUniqueSpecies} distinct Pokémon badge(s)"
                        : $"{user.Name} has collected {numUniqueSpecies} distinct Pokémon badge(s)"
                });
            }

            string mode = optionalMode.Value.ToLower();
            ImmutableSortedDictionary <PkmnSpecies, int> numBadgesPerSpecies =
                await _badgeRepo.CountByUserPerSpecies(user.Id);

            if (mode.Equals(PokedexModeMissing))
            {
                IEnumerable <PkmnSpecies> missingList     = _knownSpecies.Except(numBadgesPerSpecies.Keys);
                IEnumerable <string>      badgesFormatted = missingList.Select(entry => $"{entry}");
                return(new CommandResult
                {
                    Response = isSelf
                        ? $"You are currently missing the following badge(s): {string.Join(", ", badgesFormatted)}"
                        : $"{user.Name} is currently missing the following badge(s): {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (mode.Equals(PokedexModeDupes))
            {
                var dupeList = numBadgesPerSpecies.Where(kvp => kvp.Value > 1).ToList();
                if (!dupeList.Any())
                {
                    return(new CommandResult
                    {
                        Response = isSelf
                            ? $"You do not own any duplicate Pokémon badges"
                            : $"{user.Name} does not own any duplicate Pokémon badges"
                    });
                }
                IEnumerable <string> badgesFormatted = dupeList.Select(kvp => $"{kvp.Key}");
                return(new CommandResult
                {
                    Response = isSelf
                        ? $"You are owning duplicates of the following badge(s): {string.Join(", ", badgesFormatted)}"
                        : $"{user.Name} owns duplicates of the following badge(s): {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (mode.Equals(PokedexModeComplementFromDupes))
            {
                if (!optionalCompareUser.IsPresent)
                {
                    return(new CommandResult
                    {
                        Response = $"Mode {PokedexModeComplementFromDupes} requires a second user argument"
                    });
                }
                ImmutableSortedDictionary <PkmnSpecies, int> compareUser =
                    await _badgeRepo.CountByUserPerSpecies(optionalCompareUser.Value.Id);

                var compareUserDupeList = compareUser.Where(kvp => kvp.Value > 1).Select(kvp => kvp.Key);

                var differenceList = compareUserDupeList.Except(numBadgesPerSpecies.Keys).ToList();
                if (!differenceList.Any())
                {
                    return(new CommandResult
                    {
                        Response = $"{optionalCompareUser.Value.Name} does not own any duplicate Pokémon badges {user.Name} is missing"
                    });
                }
                IEnumerable <string> badgesFormatted = differenceList.Select(entry => $"{entry}");
                return(new CommandResult
                {
                    Response = $"{optionalCompareUser.Value.Name} owns the following duplicate badge(s) {user.Name} is missing: {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (mode.Equals(PokedexModeComplementFrom))
            {
                if (!optionalCompareUser.IsPresent)
                {
                    return(new CommandResult
                    {
                        Response = $"Mode {PokedexModeComplementFrom} requires a second user argument"
                    });
                }
                ImmutableSortedDictionary <PkmnSpecies, int> compareUser =
                    await _badgeRepo.CountByUserPerSpecies(optionalCompareUser.Value.Id);

                var differenceList = compareUser.Keys.Except(numBadgesPerSpecies.Keys).ToList();
                if (!differenceList.Any())
                {
                    return(new CommandResult
                    {
                        Response = $"{optionalCompareUser.Value.Name} does not own any Pokémon badges {user.Name} is missing"
                    });
                }
                IEnumerable <string> badgesFormatted = differenceList.Select(entry => $"{entry}");
                return(new CommandResult
                {
                    Response = $"{optionalCompareUser.Value.Name} owns the following badge(s) {user.Name} is missing: {string.Join(", ", badgesFormatted)}",
                    ResponseTarget = ResponseTarget.WhisperIfLong
                });
            }
            else if (_pokedexModeRegions.ContainsKey(mode))
            {
                RegionInformation regionInformation = _pokedexModeRegions[mode];
                ImmutableSortedDictionary <PkmnSpecies, int> ownedPokemons = (await _badgeRepo.CountByUserPerSpecies(user.Id));
                int userOwnedRegionCount = mode.Equals(PokedexModeNational)
                    ? ownedPokemons.Count(ownedPokemon => ownedPokemon.Key.GetGeneration() != regionInformation.Generation)
                    : ownedPokemons.Count(ownedPokemon => ownedPokemon.Key.GetGeneration() == regionInformation.Generation);
                return(new CommandResult
                {
                    Response = isSelf
                        ? $"You have collected {userOwnedRegionCount}/{regionInformation.TotalRegionCount} "
                               + $"distinct {mode[0].ToString().ToUpper() + mode[1..].ToLower()} badge(s)"
Example #18
0
        public override async Task RemoveAsync(IImmutableSet <IProjectTree> nodes,
                                               DeleteOptions deleteOptions = DeleteOptions.None)
        {
            if (deleteOptions.HasFlag(DeleteOptions.DeleteFromStorage))
            {
                throw new NotSupportedException();
            }

            // Get the list of shared import nodes.
            IEnumerable <IProjectTree> sharedImportNodes = nodes.Where(node =>
                                                                       node.Flags.Contains(DependencyTreeFlags.SharedProjectFlags));

            // Get the list of normal reference Item Nodes (this excludes any shared import nodes).
            IEnumerable <IProjectTree> referenceItemNodes = nodes.Except(sharedImportNodes);

            await _projectAccessor.OpenProjectForWriteAsync(ActiveConfiguredProject, project =>
            {
                // Handle the removal of normal reference Item Nodes (this excludes any shared import nodes).
                foreach (IProjectTree node in referenceItemNodes)
                {
                    if (node.BrowseObjectProperties?.Context == null)
                    {
                        // if node does not have an IRule with valid ProjectPropertiesContext we can not
                        // get its itemsSpec. If nodes provided by custom IProjectDependenciesSubTreeProvider
                        // implementation, and have some custom IRule without context, it is not a problem,
                        // since they would not have DependencyNode.GenericDependencyFlags and we would not
                        // end up here, since CanRemove would return false and Remove command would not show
                        // up for those nodes.
                        continue;
                    }

                    IProjectPropertiesContext nodeItemContext = node.BrowseObjectProperties.Context;
                    ProjectItem unresolvedReferenceItem       = project.GetItemsByEvaluatedInclude(nodeItemContext.ItemName)
                                                                .FirstOrDefault(
                        (item, t) => string.Equals(item.ItemType, t, StringComparisons.ItemTypes),
                        nodeItemContext.ItemType);

                    Report.IfNot(unresolvedReferenceItem != null, "Cannot find reference to remove.");
                    if (unresolvedReferenceItem != null)
                    {
                        project.RemoveItem(unresolvedReferenceItem);
                    }
                }

                IDependenciesSnapshot snapshot = _dependenciesSnapshotProvider.CurrentSnapshot;
                Requires.NotNull(snapshot, nameof(snapshot));
                if (snapshot == null)
                {
                    return;
                }

                // Handle the removal of shared import nodes.
                ProjectRootElement projectXml = project.Xml;
                foreach (IProjectTree sharedImportNode in sharedImportNodes)
                {
                    string sharedFilePath = UnconfiguredProject.MakeRelative(sharedImportNode.FilePath);
                    if (string.IsNullOrEmpty(sharedFilePath))
                    {
                        continue;
                    }

                    IDependency?sharedProjectDependency = snapshot.FindDependency(sharedFilePath, topLevel: true);
                    if (sharedProjectDependency != null)
                    {
                        sharedFilePath = sharedProjectDependency.Path;
                    }

                    // Find the import that is included in the evaluation of the specified ConfiguredProject that
                    // imports the project file whose full path matches the specified one.
                    IEnumerable <ResolvedImport> matchingImports = from import in project.Imports
                                                                   where import.ImportingElement.ContainingProject == projectXml &&
                                                                   PathHelper.IsSamePath(import.ImportedProject.FullPath, sharedFilePath)
                                                                   select import;
                    foreach (ResolvedImport importToRemove in matchingImports)
                    {
                        ProjectImportElement importingElementToRemove = importToRemove.ImportingElement;
                        Report.IfNot(importingElementToRemove != null,
                                     "Cannot find shared project reference to remove.");
                        if (importingElementToRemove != null)
                        {
                            importingElementToRemove.Parent.RemoveChild(importingElementToRemove);
                        }
                    }
                }
            });
        }
 private static IImmutableSet <ResourceFieldAttribute> RemoveRelationships(IImmutableSet <ResourceFieldAttribute> fieldSet)
 {
     ResourceFieldAttribute[] relationships = fieldSet.Where(field => field is RelationshipAttribute).ToArray();
     return(fieldSet.Except(relationships));
 }