Esempio n. 1
0
            private ImmutableHashSet <RemoteObserver> RemoveExcludedObservers(ImmutableHashSet <RemoteObserver> observers, PublishOptions options)
            {
                ImmutableHashSet <RemoteObserver> result = observers;

                if (options.Exclude != null)
                {
                    var excludedObservers =
                        options.Exclude.Select
                            (sessionId => new RemoteObserver(sessionId));

                    result = result.Except(excludedObservers);
                }

                if (options.ExcludeAuthenticationIds != null)
                {
                    ImmutableHashSet <RemoteObserver> excludedAuthenticationIds =
                        GatherObservers(mAuthenticationIdToSubscription,
                                        options.ExcludeAuthenticationIds);

                    result = result.Except(excludedAuthenticationIds);
                }

                if (options.ExcludeAuthenticationRoles != null)
                {
                    ImmutableHashSet <RemoteObserver> excludedAuthenticationRoles =
                        GatherObservers(mAuthenticationRoleToSubscription,
                                        options.ExcludeAuthenticationRoles);

                    result = result.Except(excludedAuthenticationRoles);
                }

                return(result);
            }
        public override void VisitView(ResolvedTreeRoot view)
        {
            var original = requiredResources;

            base.VisitView(view);
            if (original != requiredResources)
            {
                view.Content.AddRange(
                    requiredResources.Except(original).Select(r => CreateRequiredResourceControl(r, view.DothtmlNode, view.Content.First().DataContextTypeStack)));
                requiredResources = original;
            }
        }
 internal static void AddRouteBackList(IEnumerable <string> list)
 {
     if (list != null)
     {
         Allowlist = Allowlist.Except(list);
     }
 }
Esempio n. 4
0
            public IEnumerable <RemoteObserver> GetRelevantSubscribers(PublishOptions options)
            {
                ImmutableHashSet <RemoteObserver> result = mRemoteObservers;

                if (options.Eligible != null)
                {
                    var eligibleObservers =
                        GetRemoteObservers(options.Eligible)
                        .ToArray();

                    result = ImmutableHashSet.Create(eligibleObservers);
                }

                bool excludeMe = options.ExcludeMe ?? true;

                PublishOptionsExtended casted = options as PublishOptionsExtended;

                if (excludeMe && casted != null)
                {
                    result = result.Remove(new RemoteObserver(casted.PublisherId));
                }

                if (options.Exclude != null)
                {
                    var excludedObservers =
                        options.Exclude.Select
                            (sessionId => new RemoteObserver(sessionId));

                    result = result.Except(excludedObservers);
                }

                return(result);
            }
Esempio n. 5
0
        public static CardRatings Load(MemCheckDbContext dbContext, Guid userId, ImmutableHashSet <Guid> cardIds)
        {
            var allCardsAverageRatings = dbContext.UserCardRatings
                                         .AsNoTracking()
                                         .GroupBy(userRating => userRating.CardId)
                                         .Select(grouping => new { cardId = grouping.Key, averageRating = grouping.Average(grouping => grouping.Rating) })
                                         .ToList(); //Filtering in memory, not on DB, is major for perf
            var selectedCardsActualRatings = allCardsAverageRatings.Where(r => cardIds.Contains(r.cardId)).ToImmutableDictionary(average => average.cardId, average => average.averageRating);

            var allCardsRatingCounts = dbContext.UserCardRatings
                                       .AsNoTracking()
                                       .GroupBy(userRating => userRating.CardId)
                                       .Select(grouping => new { cardId = grouping.Key, count = grouping.Count() })
                                       .ToList(); //Filtering in memory, not on DB, is major for perf
            var selectedCardsRatingCounts = allCardsRatingCounts.Where(r => cardIds.Contains(r.cardId)).ToImmutableDictionary(item => item.cardId, item => item.count);

            var allRatingsOfUser = dbContext.UserCardRatings
                                   .AsNoTracking()
                                   .Where(rating => rating.UserId == userId)
                                   .Select(rating => new { cardId = rating.CardId, rating = rating.Rating })
                                   .ToList(); //Filtering in memory, not on DB, is major for perf
            var selectedCardsRatingsOfUser = allRatingsOfUser.Where(r => cardIds.Contains(r.cardId)).ToImmutableDictionary(item => item.cardId, item => item.rating);

            var cardsWithoutEval = cardIds.Except(selectedCardsActualRatings.Keys).ToImmutableHashSet();

            return(new CardRatings(selectedCardsActualRatings, selectedCardsRatingsOfUser, selectedCardsRatingCounts, cardsWithoutEval));
        }
Esempio n. 6
0
            public bool Equals(ImmutableHashSet <AssemblyName> x, ImmutableHashSet <AssemblyName> y)
            {
                if (x.Count != y.Count)
                {
                    return(false);
                }

                return(!x.Except(y).Any());
            }
Esempio n. 7
0
        public void ImmutableSetAdapter_Ctor_Succeeds()
        {
            const int NumberOfMethods = 17;

            int[] methodsCalled            = new int[NumberOfMethods];
            ImmutableHashSet <int> realSet = ImmutableHashSet <int> .Empty;

            System.Collections.Immutable.IImmutableSet <int> backingSet =
                new MockSystemImmutableSet <int>(
                    addDelegate: x => { methodsCalled[0]++; return(realSet.Add(x)); },
                    clearDelegate: () => { methodsCalled[1]++; return(realSet.Clear()); },
                    containsDelegate: x => { methodsCalled[2]++; return(realSet.Contains(x)); },
                    countDelegate: () => { methodsCalled[3]++; return(realSet.Count); },
                    equalsDelegate: null,
                    exceptDelegate: x => { methodsCalled[4]++; return(realSet.Except(x)); },
                    getEnumeratorDelegate: () => { methodsCalled[5]++; return(realSet.GetEnumerator()); },
                    getHashCodeDelegate: null,
                    intersectDelegate: x => { methodsCalled[6]++; return(realSet.Intersect(x)); },
                    isProperSubsetOfDelegate: x => { methodsCalled[7]++; return(realSet.IsProperSubsetOf(x)); },
                    isProperSupersetOfDelegate: x => { methodsCalled[8]++; return(realSet.IsProperSupersetOf(x)); },
                    isSubsetOfDelegate: x => { methodsCalled[9]++; return(realSet.IsSubsetOf(x)); },
                    isSupersetOfDelegate: x => { methodsCalled[10]++; return(realSet.IsSupersetOf(x)); },
                    overlapsDelegate: x => { methodsCalled[11]++; return(realSet.Overlaps(x)); },
                    removeDelegate: x => { methodsCalled[12]++; return(realSet.Remove(x)); },
                    setEqualsDelegate: x => { methodsCalled[13]++; return(realSet.SetEquals(x)); },
                    symmetricExceptDelegate: x => { methodsCalled[14]++; return(realSet.SymmetricExcept(x)); },
                    toStringDelegate: null,
                    tryGetValueDelegate: (int x, out int y) => { methodsCalled[15]++; return(realSet.TryGetValue(x, out y)); },
                    unionDelegate: x => { methodsCalled[16]++; return(realSet.Union(x)); });

#pragma warning disable IDE0028 // Simplify collection initialization. Intentionally calling .Add separately for clarity
            ImmutableSetAdapter <int> set = new ImmutableSetAdapter <int>(backingSet);
#pragma warning restore IDE0028 // Simplify collection initialization.

            set.Add(12);
            set.Clear();
            set.Contains(12);
            _ = set.Count;
            set.Except(Array.Empty <int>());
            set.GetEnumerator();
            set.Intersect(Array.Empty <int>());
            set.IsProperSubsetOf(Array.Empty <int>());
            set.IsProperSupersetOf(Array.Empty <int>());
            set.IsSubsetOf(Array.Empty <int>());
            set.IsSupersetOf(Array.Empty <int>());
            set.Overlaps(Array.Empty <int>());
            set.Remove(12);
            set.SetEquals(Array.Empty <int>());
            set.SymmetricExcept(Array.Empty <int>());
            set.TryGetValue(12, out _);
            set.Union(Array.Empty <int>());

            for (int counter = 0; counter < NumberOfMethods; counter++)
            {
                Assert.AreEqual(1, methodsCalled[counter]);
            }
        }
Esempio n. 8
0
        public LanguageSyntax(IEnumerable <string> rootTags, IEnumerable <Tag> tags, char escapeChar)
        {
            EscapeChar    = escapeChar;
            this.rootTags = rootTags.ToImmutableHashSet();
            this.tags     = tags.ToImmutableDictionary(c => c.Name, c => c);
            Alphabet      = this.tags.Select(p => p.Key).Union(this.rootTags).ToImmutableHashSet();
            var notDescribedTags = Alphabet.Except(this.tags.Select(p => p.Key));

            if (notDescribedTags.Count != 0)
            {
                throw new IncorrectSyntaxException($"Not all tags has been described: {notDescribedTags.SequenceToString()}");
            }
        }
        private void Visit <TNodeType>(TNodeType node, List <ResolvedControl> nodeContent, Action <TNodeType> visitBase) where TNodeType : ResolvedTreeNode
        {
            var original = requiredResources;

            visitBase(node);
            if (original != requiredResources)
            {
                nodeContent.AddRange(
                    requiredResources
                    .Except(original)
                    .Select(name => CreateRequiredResourceControl(name, node.DothtmlNode, nodeContent.First().DataContextTypeStack)));
                requiredResources = original;
            }
        }
        private static void  TryToReportMissingMembers(SyntaxNodeAnalysisContext context,
                                                       InitializerExpressionSyntax initializer, ImmutableHashSet <string> membersForInitialization,
                                                       Location getLocation)
        {
            var alreadyInitializedMembers = GetAlreadyInitializedMembers(initializer);
            var missingMembers            = membersForInitialization.Except(alreadyInitializedMembers);

            if (missingMembers.IsEmpty == false)
            {
                var missingMembersList = string.Join("\r\n", missingMembers.Select(x => $"- {x}"));

                var diagnostic = Diagnostic.Create(Rule, getLocation, missingMembersList);
                context.ReportDiagnostic(diagnostic);
            }
        }
Esempio n. 11
0
        public async Task RemoveRoute(string id)
        {
            this.CheckClosed();

            using (await this.sync.LockAsync(this.cts.Token))
            {
                this.CheckClosed();
                ImmutableDictionary <string, Route> snapshot         = this.routes;
                ImmutableHashSet <Endpoint>         currentEndpoints = this.Routes.SelectMany(r => r.Endpoints).ToImmutableHashSet();
                this.routes.GetAndSet(snapshot.Remove(id));
                ISet <string> removedEndpointIds = currentEndpoints.Except(this.Routes.SelectMany(r => r.Endpoints))
                                                   .Select(e => e.Id)
                                                   .ToImmutableHashSet();

                this.evaluator.RemoveRoute(id);
                await this.dispatcher.RemoveEndpoints(removedEndpointIds);
            }
        }
Esempio n. 12
0
        private static IEnumerable <ImmutableHashSet <T> > FindCliques(
            IGraph <T> graph,
            ImmutableHashSet <T> potential_clique,
            ImmutableHashSet <T> remaining_nodes,
            ImmutableHashSet <T> skip_nodes)
        {
            if (potential_clique.IsEmpty && skip_nodes.IsEmpty)
            {
                yield return(remaining_nodes);
            }
            else
            {
                var choices = potential_clique.Union(skip_nodes);
                ImmutableHashSet <T> pivoted;

                if (choices.Count > 0)
                {
                    var pivotVertex = choices.Shuffle().First();
                    pivoted = potential_clique.Except(graph.Neigbours(pivotVertex));
                }
                else
                {
                    pivoted = potential_clique;
                }

                foreach (var v in pivoted)
                {
                    var neighborsOfV = graph.Neigbours(v);
                    var sub          = FindCliques(
                        graph,
                        potential_clique.Intersect(neighborsOfV),
                        remaining_nodes.Add(v),
                        skip_nodes.Intersect(neighborsOfV));

                    foreach (var s in sub)
                    {
                        yield return(s);
                    }

                    potential_clique = potential_clique.Remove(v);
                    skip_nodes       = skip_nodes.Add(v);
                }
            }
        }
Esempio n. 13
0
        public void Process(ImmutableHashSet <EvalStack> set)
        {
            if (G == null)
            {
                throw new NullReferenceException("Need to init G for node " + _id);
            }

            var x = set.Except(_I);

            if (!x.IsEmpty)
            {
                _I = _I.Union(x);
                _O = _I.Select(s => G(s)).ToImmutableHashSet();
                foreach (var n in _targets)
                {
                    n.Process(_O);
                }
            }
        }
Esempio n. 14
0
            public bool Equals(ImmutableHashSet <AssemblyName>?x, ImmutableHashSet <AssemblyName>?y)
            {
                if (x == y)
                {
                    return(true);
                }

                if (x is null || y is null)
                {
                    return(false);
                }

                if (x.Count != y.Count)
                {
                    return(false);
                }

                return(!x.Except(y).Any());
            }
        private static void ReportDisposeMethods(ImmutableHashSet <IMethodSymbol> allDisposeMethods, ImmutableHashSet <IMethodSymbol> implementingDisposeMethods,
                                                 ImmutableDictionary <INamedTypeSymbol, ImmutableHashSet <IMethodSymbol> > disposeMethodsCalledFromDispose, CompilationAnalysisContext c)
        {
            foreach (var dispose in allDisposeMethods.Except(implementingDisposeMethods))
            {
                if (MethodCalledFromDispose(disposeMethodsCalledFromDispose, dispose))
                {
                    continue;
                }

                foreach (var declaringSyntaxReference in dispose.DeclaringSyntaxReferences)
                {
                    var methodDeclaration =
                        declaringSyntaxReference.GetSyntax() as MethodDeclarationSyntax;
                    if (methodDeclaration != null)
                    {
                        c.ReportDiagnosticIfNonGenerated(Diagnostic.Create(Rule, methodDeclaration.Identifier.GetLocation()));
                    }
                }
            }
        }
        /// <summary>
        ///     Constructs validator with custom set of allowed and restricted characters.
        /// </summary>
        /// <param name="configAction">
        ///     Delegate to configure validator. Used for setting allowed characters and add additional restricted characters.
        /// </param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="configAction" /> is null.</exception>
        /// <exception cref="ArgumentException">Thrown if you set same characters for allowed and restricted.</exception>
        public NoSpecialCharactersValidator(Action <INoSpecialCharactersConfigurationExpression> configAction) : this()
        {
            if (configAction == null)
            {
                throw new ArgumentNullException(nameof(configAction));
            }

            var builder = new NoSpecialCharactersConfigurationBuilder();

            configAction(builder);
            _configuration = builder.Build();

            if (_configuration.AllowedChars != null && _configuration.AllowedChars.Count > 0)
            {
                _restrictedCharacters = _restrictedCharacters.Except(_configuration.AllowedChars);
            }

            if (_configuration.RestrictedChars != null && _configuration.RestrictedChars.Count > 0)
            {
                _restrictedCharacters = _restrictedCharacters.Union(_configuration.RestrictedChars);
            }
        }
        /// <summary>
        /// Creates a change-based checkbox list, which is a checkbox list that is based on changes to the selections rather than the absolute set of selected
        /// items.
        /// </summary>
        /// <param name="items">The items in the list.</param>
        /// <param name="selectedItemIds">The selected-item IDs.</param>
        /// <param name="modificationMethod">A method that executes the change handlers of the items that were selected or deselected on this post back.</param>
        /// <param name="displaySetup"></param>
        /// <param name="includeSelectAndDeselectAllButtons"></param>
        /// <param name="minColumnWidth">The minimum width of each column in the list. Pass null to force a single column.</param>
        /// <param name="uiSelectedItemIds"></param>
        /// <param name="action">The action that will occur when the user hits Enter on any of the checkboxes. Pass null to use the current default action.</param>
        /// <param name="selectionChangedAction">The action that will occur when the selection is changed. Pass null for no action.</param>
        /// <param name="validationPredicate"></param>
        /// <param name="validationErrorNotifier"></param>
        public static CheckboxList <ItemIdType> Create <ItemIdType>(
            IEnumerable <ChangeBasedListItem <ItemIdType> > items, IEnumerable <ItemIdType> selectedItemIds, out Action modificationMethod,
            DisplaySetup displaySetup = null, bool includeSelectAndDeselectAllButtons             = false, ContentBasedLength minColumnWidth = null,
            IEnumerable <ItemIdType> uiSelectedItemIds = null, SpecifiedValue <FormAction> action = null, FormAction selectionChangedAction  = null,
            Func <bool, bool> validationPredicate      = null, Action validationErrorNotifier     = null)
        {
            items = items.Materialize();
            var selectedItemIdSet = selectedItemIds.ToImmutableHashSet();

            ImmutableHashSet <ItemIdType> selectedItemIdsInPostBack = null;

            modificationMethod = () => {
                if (selectedItemIdsInPostBack == null)
                {
                    return;
                }
                var changedItemIds = selectedItemIdsInPostBack.Except(selectedItemIdSet).Union(selectedItemIdSet.Except(selectedItemIdsInPostBack)).ToArray();
                foreach (var i in items.Where(i => changedItemIds.Contains(i.Item.Id)))
                {
                    i.ChangeHandler(selectedItemIdsInPostBack.Contains(i.Item.Id));
                }
            };

            return(new CheckboxList <ItemIdType>(
                       CheckboxListSetup.Create(
                           from i in items select i.Item,
                           displaySetup: displaySetup,
                           includeSelectAndDeselectAllButtons: includeSelectAndDeselectAllButtons,
                           minColumnWidth: minColumnWidth,
                           action: action,
                           selectionChangedAction: selectionChangedAction,
                           validationPredicate: validationPredicate,
                           validationErrorNotifier: validationErrorNotifier),
                       uiSelectedItemIds ?? selectedItemIdSet,
                       validationMethod: (postBackValue, validator) => selectedItemIdsInPostBack = postBackValue.ToImmutableHashSet()));
        }
        private static void ReportDisposeMethods(ImmutableHashSet<IMethodSymbol> allDisposeMethods, ImmutableHashSet<IMethodSymbol> implementingDisposeMethods,
            ImmutableDictionary<INamedTypeSymbol, ImmutableHashSet<IMethodSymbol>> disposeMethodsCalledFromDispose, CompilationAnalysisContext c)
        {
            foreach (var dispose in allDisposeMethods.Except(implementingDisposeMethods))
            {
                if (MethodCalledFromDispose(disposeMethodsCalledFromDispose, dispose))
                {
                    continue;
                }

                foreach (var declaringSyntaxReference in dispose.DeclaringSyntaxReferences)
                {
                    var methodDeclaration =
                        declaringSyntaxReference.GetSyntax() as MethodDeclarationSyntax;
                    if (methodDeclaration != null)
                    {
                        c.ReportDiagnostic(Diagnostic.Create(Rule, methodDeclaration.Identifier.GetLocation()));
                    }
                }
            }
        }
Esempio n. 19
0
 public TestComposition RemoveExcludedPartTypes(IEnumerable <Type>?types)
 => WithExcludedPartTypes(ExcludedPartTypes.Except(types ?? Array.Empty <Type>()));
Esempio n. 20
0
 public TestComposition RemoveParts(IEnumerable <Type>?types)
 => WithParts(Parts.Except(types ?? Array.Empty <Type>()));
Esempio n. 21
0
 public TestComposition RemoveAssemblies(IEnumerable <Assembly>?assemblies)
 => WithAssemblies(Assemblies.Except(assemblies ?? Array.Empty <Assembly>()));
 public static ImmutableHashSet <T> RemoveRange <T>(this ImmutableHashSet <T> set, IEnumerable <T> values)
 {
     return(set.Except(values));
 }
Esempio n. 23
0
 /// <inheritdoc />
 public IImmutableSet <T> Except(IEnumerable <T> other)
 {
     return(new SetEqualedReadOnlySet <T>(_set.Except(other)));
 }
        /// <summary>
        ///     Provide completions for the specified location.
        /// </summary>
        /// <param name="location">
        ///     The <see cref="XmlLocation"/> where completions are requested.
        /// </param>
        /// <param name="projectDocument">
        ///     The <see cref="ProjectDocument"/> that contains the <paramref name="location"/>.
        /// </param>
        /// <param name="cancellationToken">
        ///     A <see cref="CancellationToken"/> that can be used to cancel the operation.
        /// </param>
        /// <returns>
        ///     A <see cref="Task{TResult}"/> that resolves either a <see cref="CompletionList"/>s, or <c>null</c> if no completions are provided.
        /// </returns>
        public override async Task <CompletionList> ProvideCompletions(XmlLocation location, ProjectDocument projectDocument, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (location == null)
            {
                throw new ArgumentNullException(nameof(location));
            }

            if (projectDocument == null)
            {
                throw new ArgumentNullException(nameof(projectDocument));
            }

            List <CompletionItem> completions = new List <CompletionItem>();

            using (await projectDocument.Lock.ReaderLockAsync())
            {
                XSElement   element;
                XSAttribute replaceAttribute;
                PaddingType needsPadding;
                if (!location.CanCompleteAttribute(out element, out replaceAttribute, out needsPadding))
                {
                    return(null);
                }

                // Must be a valid item element.
                if (!element.IsValid || !element.HasParentPath(WellKnownElementPaths.ItemGroup))
                {
                    return(null);
                }

                Range replaceRange = replaceAttribute?.Range ?? location.Position.ToEmptyRange();

                completions.AddRange(
                    WellKnownItemAttributes.Except(
                        element.AttributeNames
                        )
                    .Select(attributeName => new CompletionItem
                {
                    Label         = attributeName,
                    Detail        = "Attribute",
                    Documentation =
                        MSBuildSchemaHelp.ForItemMetadata(itemType: element.Name, metadataName: attributeName)
                        ??
                        MSBuildSchemaHelp.ForAttribute(element.Name, attributeName),
                    Kind     = CompletionItemKind.Field,
                    SortText = GetItemSortText(attributeName),
                    TextEdit = new TextEdit
                    {
                        NewText = $"{attributeName}=\"$1\"$0".WithPadding(needsPadding),
                        Range   = replaceRange.ToLsp()
                    },
                    InsertTextFormat = InsertTextFormat.Snippet
                })
                    );
            }

            if (completions.Count == 0)
            {
                return(null);
            }

            return(new CompletionList(completions, isIncomplete: false));
        }
Esempio n. 25
0
 public ImmutableHashSet <IPhotonWirePeer> GetExceptPeers(IEnumerable <IPhotonWirePeer> peers)
 {
     return(currentHandlers.Except(Verify(peers)));
 }
Esempio n. 26
0
        internal static bool InitPlugins()
        {
            string pluginsPath = Path.Combine(SharedInfo.HomeDirectory, SharedInfo.PluginsDirectory);

            if (!Directory.Exists(pluginsPath))
            {
                ASF.ArchiLogger.LogGenericTrace(Strings.NothingFound);

                return(true);
            }

            ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.Initializing, nameof(Plugins)));

            HashSet <Assembly> assemblies = new HashSet <Assembly>();

            try {
                foreach (string assemblyPath in Directory.EnumerateFiles(pluginsPath, "*.dll"))
                {
                    Assembly assembly;

                    try {
                        assembly = Assembly.LoadFrom(assemblyPath);
                    } catch (Exception e) {
                        ASF.ArchiLogger.LogGenericException(e);

                        continue;
                    }

                    assemblies.Add(assembly);
                }
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);

                return(false);
            }

            if (assemblies.Count == 0)
            {
                ASF.ArchiLogger.LogGenericInfo(Strings.NothingFound);

                return(true);
            }

            ConventionBuilder conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IPlugin>().Export <IPlugin>();

            ContainerConfiguration configuration = new ContainerConfiguration().WithAssemblies(assemblies, conventions);

            try {
                using (CompositionHost container = configuration.CreateContainer()) {
                    ActivePlugins = container.GetExports <IPlugin>().ToImmutableHashSet();
                }
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);

                return(false);
            }

            HashSet <IPlugin> invalidPlugins = new HashSet <IPlugin>();

            foreach (IPlugin plugin in ActivePlugins)
            {
                try {
                    string pluginName = plugin.Name;

                    ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.PluginLoading, pluginName, plugin.Version));
                    plugin.OnLoaded();
                    ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.PluginLoaded, pluginName));
                } catch (Exception e) {
                    ASF.ArchiLogger.LogGenericException(e);
                    invalidPlugins.Add(plugin);
                }
            }

            ImmutableHashSet <IPlugin> activePlugins = ActivePlugins.Except(invalidPlugins);

            if (activePlugins.Count == 0)
            {
                ActivePlugins = null;

                return(false);
            }

            ActivePlugins = activePlugins;
            ASF.ArchiLogger.LogGenericInfo(Strings.PluginsWarning);

            return(invalidPlugins.Count == 0);
        }
Esempio n. 27
0
        // FIXME it's very dangerous because replacing Id means
        // ALL blocks (referenced by MineBlock(), etc.) will be changed.
        internal System.Action Swap(
            BlockChain <T> other,
            bool render,
            StateCompleterSet <T>?stateCompleters = null)
        {
            if (other is null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            // As render/unrender processing requires every step's states from the branchpoint
            // to the new/stale tip, incomplete states need to be complemented anyway...
            StateCompleterSet <T> completers = stateCompleters ?? StateCompleterSet <T> .Recalculate;

            if (Tip.Equals(other.Tip))
            {
                // If it's swapped for a chain with the same tip, it means there is no state change.
                // Hence render is unnecessary.
                render = false;
            }
            else
            {
                _logger.Debug(
                    "The blockchain was reorged from " +
                    "{OldChainId} (#{OldTipIndex} {OldTipHash}) " +
                    "to {NewChainId} (#{NewTipIndex} {NewTipHash}).",
                    Id,
                    Tip.Index,
                    Tip.Hash,
                    other.Id,
                    other.Tip.Index,
                    other.Tip.Hash);
            }

            System.Action renderSwap = () => { };

            _rwlock.EnterUpgradeableReadLock();
            try
            {
                // Finds the branch point.
                Block <T> branchpoint = FindTopCommon(this, other);

                if (branchpoint is null)
                {
                    const string msg =
                        "A chain cannot be reorged into a heterogeneous chain with a " +
                        "different genesis.";
                    throw new InvalidGenesisBlockException(Genesis.Hash, other.Genesis.Hash, msg);
                }

                _logger.Debug(
                    "The branchpoint is #{BranchpointIndex} {BranchpointHash}.",
                    branchpoint.Index,
                    branchpoint
                    );

                Block <T> oldTip = Tip, newTip = other.Tip;

                ImmutableList <Block <T> > rewindPath      =
                    GetRewindPath(this, branchpoint.Hash);
                ImmutableList <Block <T> > fastForwardPath =
                    GetFastForwardPath(other, branchpoint.Hash);

                // If there is no rewind, it is not considered as a reorg.
                bool reorg = rewindPath.Count > 0;

                _rwlock.EnterWriteLock();
                try
                {
                    IEnumerable <Transaction <T> >
                    GetTxsWithRange(BlockChain <T> chain, Block <T> start, Block <T> end)
                    => Enumerable
                    .Range((int)start.Index + 1, (int)(end.Index - start.Index))
                    .SelectMany(x =>
                    {
                        // FIXME: Change the type of IBlockContent<T>.Transactions to
                        // IImmutableSet<Transaction<T>>, and define a distinct property
                        // to Block<T> for this ordering.
                        Block <T> block = chain[x];
                        return(ActionEvaluator <T> .OrderTxsForEvaluation(
                                   block.ProtocolVersion,
                                   block.Transactions,
                                   block.PreEvaluationHash
                                   ));
                    });

                    // It assumes reorg is small size. If it was big, this may be heavy task.
                    ImmutableHashSet <Transaction <T> > unstagedTxs =
                        GetTxsWithRange(this, branchpoint, Tip).ToImmutableHashSet();
                    ImmutableHashSet <Transaction <T> > stageTxs =
                        GetTxsWithRange(other, branchpoint, other.Tip).ToImmutableHashSet();
                    ImmutableHashSet <Transaction <T> > restageTxs = unstagedTxs.Except(stageTxs);
                    foreach (Transaction <T> restageTx in restageTxs)
                    {
                        StagePolicy.Stage(this, restageTx);
                    }

                    Guid obsoleteId = Id;
                    Id = other.Id;
                    Store.SetCanonicalChainId(Id);
                    _blocks = new BlockSet <T>(Policy.GetHashAlgorithm, Store);
                    TipChanged?.Invoke(this, (oldTip, newTip));

                    Store.DeleteChainId(obsoleteId);
                }
                finally
                {
                    _rwlock.ExitWriteLock();
                }

                renderSwap = () => RenderSwap(
                    render: render,
                    oldTip: oldTip,
                    newTip: newTip,
                    branchpoint: branchpoint,
                    rewindPath: rewindPath,
                    fastForwardPath: fastForwardPath,
                    stateCompleters: completers);
            }
            finally
            {
                _rwlock.ExitUpgradeableReadLock();
            }

            return(renderSwap);
        }