Ejemplo n.º 1
0
        private static void RegisterAnalyzer(
            CompilationStartAnalysisContext context
            )
        {
            ImmutableHashSet <INamedTypeSymbol> configuredTaskTypes = ImmutableHashSet
                                                                      .Create(
                context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable"),
                context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1"),
                context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable"),
                context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1")
                )
                                                                      .Where(x => x != null && x.Kind != SymbolKind.ErrorType)
                                                                      .ToImmutableHashSet();

            if (!configuredTaskTypes.Any())
            {
                return;
            }

            context.RegisterOperationAction(
                ctx => AnalyzeAwait(
                    context: ctx,
                    configuredTaskTypes: configuredTaskTypes,
                    operation: ctx.Operation as IAwaitOperation
                    ),
                OperationKind.Await
                );
        }
Ejemplo n.º 2
0
        IDisposable IHandlersManager.AddLink(string fromMethod, string toMethod)
        {
            var source = _descriptors.FirstOrDefault(z => z.Method == fromMethod);

            if (source == null)
            {
                if (_descriptors.Any(z => z.Method == toMethod))
                {
                    throw new ArgumentException(
                              $"Could not find descriptor for '{fromMethod}', but I did find one for '{toMethod}'.  Did you mean to link '{toMethod}' to '{fromMethod}' instead?", fromMethod
                              );
                }

                throw new ArgumentException(
                          $"Could not find descriptor for '{fromMethod}', has it been registered yet?  Descriptors must be registered before links can be created!", nameof(fromMethod)
                          );
            }

            HandlerDescriptor descriptor = null;

            descriptor = GetDescriptor(
                toMethod,
                source.HandlerType,
                source.Handler,
                source.RequestProcessType.HasValue ? new JsonRpcHandlerOptions {
                RequestProcessType = source.RequestProcessType.Value
            } : null,
                source.TypeDescriptor,
                source.HandlerType
                );
            Interlocked.Exchange(ref _descriptors, _descriptors.Add(descriptor));

            return(descriptor);
        }
Ejemplo n.º 3
0
        // Cognitive Complexity 5
        public static ContentView GetContentView(string contentId, IReadOnlyCollection <string> requestedUriTypes)
        {
            ImmutableHashSet <string> subsetUriTypes = AllSupportedUriTypes.Intersect(requestedUriTypes);

            if (!subsetUriTypes.Any())
            {
                throw new Exception("message");
            }

            return(new ContentView
            {
                ResultStatus = AllSupportedUriTypes.SetEquals(subsetUriTypes) ? ResultStatusComplete : ResultStatusPartial,
                Uris = subsetUriTypes.Select(uriType =>
                {
                    if (IsViewerA(uriType))
                    {
                        return $"https://{ViewerA}/{contentId}";
                    }
                    else if (IsViewerC(uriType))
                    {
                        return $"https://{ViewerC}/{contentId}";
                    }
                    else
                    {
                        return $"https://{ViewerD}/{contentId}";
                    }
                })
            });
        }
Ejemplo n.º 4
0
        private Receive RecoveringEvents(ImmutableHashSet <RecoveryLink> active) => message =>
        {
            if (message is ReplicationWriteSuccess writeSuccess && active.Any(link => writeSuccess.Metadata.ContainsKey(link.ReplicationLink.Source.LogId)))
            {
                foreach (var link in active)
                {
                    if (RecoveryForLinkFinished(link, writeSuccess))
                    {
                        var updatedActive = RemoveLink(active, link);
                        if (updatedActive.IsEmpty)
                        {
                            Context.Parent.Tell(new Acceptor.EventRecoveryCompleted());
                            Self.Tell(PoisonPill.Instance);
                        }
                        else
                        {
                            Context.Become(RecoveringEvents(updatedActive));
                        }

                        return(true);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
Ejemplo n.º 5
0
 public void AwaitMembersUp(
     int numbersOfMembers,
     ImmutableHashSet <Address> canNotBePartOfMemberRing = null,
     TimeSpan?timeout = null)
 {
     if (canNotBePartOfMemberRing == null)
     {
         canNotBePartOfMemberRing = ImmutableHashSet.Create <Address>();
     }
     if (timeout == null)
     {
         timeout = TimeSpan.FromSeconds(25);
     }
     Within(timeout.Value, () =>
     {
         if (canNotBePartOfMemberRing.Any()) // don't run this on an empty set
         {
             AwaitAssert(() =>
             {
                 foreach (var a in canNotBePartOfMemberRing)
                 {
                     _assertions.AssertFalse(ClusterView.Members.Select(m => m.Address).Contains(a));
                 }
             });
         }
         AwaitAssert(() => _assertions.AssertEqual(numbersOfMembers, ClusterView.Members.Count));
         AwaitAssert(() => _assertions.AssertTrue(ClusterView.Members.All(m => m.Status == MemberStatus.Up), "All members should be up"));
         // clusterView.leader is updated by LeaderChanged, await that to be updated also
         var firstMember    = ClusterView.Members.FirstOrDefault();
         var expectedLeader = firstMember == null ? null : firstMember.Address;
         AwaitAssert(() => _assertions.AssertEqual(expectedLeader, ClusterView.Leader));
     });
 }
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var invocation = context.Node as InvocationExpressionSyntax;

            if (invocation == null)
            {
                return;
            }

            var name = invocation.MethodName();


            // check if any of the "string" methods are used
            if (!StringMethods.Contains(name))
            {
                return;
            }


            // check if the method is the one from UnityEngine
            var symbolInfo   = context.SemanticModel.GetSymbolInfo(invocation);
            var methodSymbol = symbolInfo.Symbol as IMethodSymbol;

            if (Namespaces.Any(ns => methodSymbol?.ToString().StartsWith(ns) ?? false))
            {
                var diagnostic = Diagnostic.Create(DiagnosticDescriptors.DoNotUseStringMethods, invocation.GetLocation());
                context.ReportDiagnostic(diagnostic);
            }
        }
Ejemplo n.º 7
0
        public UseSiteInfo(DiagnosticInfo?diagnosticInfo, TAssemblySymbol?primaryDependency, ImmutableHashSet <TAssemblySymbol>?secondaryDependencies)
        {
            Debug.Assert(diagnosticInfo?.Severity != DiagnosticSeverity.Error || (primaryDependency is null && secondaryDependencies?.IsEmpty != false));
            Debug.Assert(primaryDependency is null || primaryDependency != primaryDependency.CorLibrary);
            Debug.Assert(secondaryDependencies?.IsEmpty != false || !secondaryDependencies.Any(dependency => dependency == dependency.CorLibrary));

            DiagnosticInfo        = diagnosticInfo;
            PrimaryDependency     = primaryDependency;
            SecondaryDependencies = secondaryDependencies ?? ImmutableHashSet <TAssemblySymbol> .Empty;
        }
Ejemplo n.º 8
0
        private void RegisterScopeBuilderAnalyzer(CompilationStartAnalysisContext context)
        {
            var ILoggingExecutionContextScopeBuilder = context.Compilation.GetTypeByMetadataName("D2L.LP.Logging.ExecutionContexts.ILoggingExecutionContextScopeBuilder");

            // ILoggingExecutionContextScopeBuilder not in compilation, no need to register
            if (ILoggingExecutionContextScopeBuilder == null || ILoggingExecutionContextScopeBuilder.Kind == SymbolKind.ErrorType)
            {
                return;
            }

            ImmutableHashSet <IMethodSymbol> ILoggingExecutionContextScopeBuilderRunSymbols = ILoggingExecutionContextScopeBuilder
                                                                                              .GetMembers()
                                                                                              .Where(m => m.Kind == SymbolKind.Method)
                                                                                              .Where(m => m.MetadataName == "Run")
                                                                                              .Cast <IMethodSymbol>()
                                                                                              .ToImmutableHashSet();

            // Can't find ILoggingExecutionContextScopeBuilder.Run or ILoggingExecutionContextScopeBuilder.Run<T>
            if (!ILoggingExecutionContextScopeBuilderRunSymbols.Any())
            {
                return;
            }

            ImmutableHashSet <INamedTypeSymbol> taskTypeBuiltins = ImmutableHashSet
                                                                   .Create(
                context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task"),
                context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1"),
                context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.ValueTask"),
                context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.ValueTask`1"),
                context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable"),
                context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1")
                )
                                                                   .Where(x => x != null && x.Kind != SymbolKind.ErrorType)
                                                                   .ToImmutableHashSet();

            // [AsyncMethodBuilder] is used to create custom awaitable types
            // See https://blogs.msdn.microsoft.com/seteplia/2018/01/11/extending-the-async-methods-in-c/
            INamedTypeSymbol AsyncMethodBuilderAttribute = context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AsyncMethodBuilderAttribute");

            context.RegisterSyntaxNodeAction(
                ctx => RunInvocationAnalysis(
                    context: ctx,
                    AsyncMethodBuilderAttribute: AsyncMethodBuilderAttribute,
                    ILoggingExecutionContextScopeBuilderRunSymbols: ILoggingExecutionContextScopeBuilderRunSymbols,
                    taskTypeBuiltins: taskTypeBuiltins,
                    invocationSyntax: ctx.Node as InvocationExpressionSyntax
                    ),
                SyntaxKind.InvocationExpression
                );
        }
        private PointsToAbstractValue(ImmutableHashSet <AbstractLocation> locations, NullAbstractValue nullState)
        {
            Debug.Assert(!locations.IsEmpty);
            Debug.Assert(locations.All(location => !location.IsNull) || nullState != NullAbstractValue.NotNull);
            Debug.Assert(nullState != NullAbstractValue.Undefined);
            Debug.Assert(nullState != NullAbstractValue.Invalid);
            Debug.Assert(!locations.Any(l => l.IsAnalysisEntityDefaultLocation && l.AnalysisEntityOpt.HasUnknownInstanceLocation));
            Debug.Assert(locations.Count <= LocationThreshold);

            Locations = locations;
            LValueCapturedOperations = ImmutableHashSet <IOperation> .Empty;
            Kind      = PointsToAbstractValueKind.KnownLocations;
            NullState = nullState;
        }
Ejemplo n.º 10
0
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            DefaultAuthorizationRequirement requirement)
        {
            ImmutableArray <IPAddress> dynamicIPAddresses = _allowedIPAddressHandler.IpAddresses;

            ImmutableHashSet <IPAddress> allAddresses = _allowed.Concat(dynamicIPAddresses).Where(ip => !Equals(ip, IPAddress.None)).ToImmutableHashSet();

            if (context.User.HasClaim(claim =>
                                      claim.Type == CustomClaimTypes.IPAddress &&
                                      allAddresses.Any(ip => claim.Value.StartsWith(ip.ToString(), StringComparison.OrdinalIgnoreCase))))
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
        public override IDependency BeforeAdd(
            string projectPath,
            ITargetFramework targetFramework,
            IDependency dependency,
            ImmutableDictionary <string, IDependency> .Builder worldBuilder,
            ImmutableHashSet <IDependency> .Builder topLevelBuilder,
            Dictionary <string, IProjectDependenciesSubTreeProvider> subTreeProviders,
            HashSet <string> projectItemSpecs,
            out bool filterAnyChanges)
        {
            filterAnyChanges = false;
            IDependency resultDependency = dependency;

            var matchingDependency = topLevelBuilder.FirstOrDefault(
                x => !x.Id.Equals(dependency.Id, StringComparison.OrdinalIgnoreCase) &&
                x.ProviderType.Equals(dependency.ProviderType, StringComparison.OrdinalIgnoreCase) &&
                x.Caption.Equals(dependency.Caption, StringComparison.OrdinalIgnoreCase));

            // if found node with same caption, or if there were nodes with same caption but with Alias already applied
            var shouldApplyAlias = (matchingDependency == null)
                ? topLevelBuilder.Any(
                x => !x.Id.Equals(dependency.Id) &&
                x.ProviderType.Equals(dependency.ProviderType, StringComparison.OrdinalIgnoreCase) &&
                x.Caption.Equals(
                    string.Format(CultureInfo.CurrentCulture, "{0} ({1})", dependency.Caption, x.OriginalItemSpec),
                    StringComparison.OrdinalIgnoreCase))
                : true;

            if (shouldApplyAlias)
            {
                filterAnyChanges = true;
                if (matchingDependency != null)
                {
                    matchingDependency = matchingDependency.SetProperties(caption: matchingDependency.Alias);
                    worldBuilder.Remove(matchingDependency.Id);
                    worldBuilder.Add(matchingDependency.Id, matchingDependency);
                    topLevelBuilder.Remove(matchingDependency);
                    topLevelBuilder.Add(matchingDependency);
                }

                resultDependency = resultDependency.SetProperties(caption: dependency.Alias);
            }

            return(resultDependency);
        }
Ejemplo n.º 12
0
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            // check if any of the "string methods" are used
            var identifierName = context.Node as IdentifierNameSyntax;

            if (!StringMethods.Contains(identifierName.Identifier.ToString()))
            {
                return;
            }

            // check if the method is the one from UnityEngine
            var methodSymbol = context.SemanticModel.GetSymbolInfo(identifierName).Symbol as IMethodSymbol;

            if (Namespaces.Any(ns => methodSymbol?.ToString().StartsWith(ns) ?? false))
            {
                var diagnostic = Diagnostic.Create(DiagnosticDescriptors.DoNotUseStringMethods, identifierName.GetLocation());
                context.ReportDiagnostic(diagnostic);
            }
        }
Ejemplo n.º 13
0
            /// <inheritdoc/>
            public override string ToString()
            {
                string FormatWatchingRefs()
                {
                    if (!_watchingRefs.Any())
                    {
                        return("");
                    }
                    return($"{string.Join(", ", _watchingRefs.Select(r => r.Item2.Path.Name + "-> " + r.Item1.Path.Name))}");
                }

                string FormatWatchingAddresses()
                {
                    if (!_watchingAddresses.Any())
                    {
                        return("");
                    }
                    return(string.Join(",", WatchingAddresses));
                }

                return($"Stats(watching={_watching}, watchingNodes={_watchingNodes}, watchingRefs=[{FormatWatchingRefs()}], watchingAddresses=[{FormatWatchingAddresses()}])");
            }
Ejemplo n.º 14
0
        private void ProcessTxIds(TxIds message)
        {
            if (!(message.Remote is BoundPeer peer))
            {
                _logger.Information(
                    $"Ignores a {nameof(TxIds)} message because it was sent by an invalid peer: " +
                    "{PeerAddress}.",
                    message.Remote?.Address.ToHex()
                    );
                return;
            }

            _logger.Debug(
                $"Received a {nameof(TxIds)} message: {{@TxIds}}.",
                message.Ids.Select(txid => txid.ToString())
                );

            IStagePolicy <T>        stagePolicy = BlockChain.StagePolicy;
            ImmutableHashSet <TxId> newTxIds    = message.Ids
                                                  .Where(id => !_demandTxIds.ContainsKey(id))
                                                  .Where(id => !stagePolicy.HasStaged(BlockChain, id, true))
                                                  .ToImmutableHashSet();

            if (!newTxIds.Any())
            {
                _logger.Debug("No unaware transactions to receive.");
                return;
            }

            _logger.Debug(
                "Unaware transactions to receive: {@TxIds}.",
                newTxIds.Select(txid => txid.ToString())
                );
            foreach (TxId txid in newTxIds)
            {
                _demandTxIds.TryAdd(txid, peer);
            }
        }
Ejemplo n.º 15
0
            public override string ToString()
            {
                Func <string> formatWatchingRefs = () =>
                {
                    if (!_watchingRefs.Any())
                    {
                        return("");
                    }
                    return
                        ($"{_watchingRefs.Select(r => r.Item2.Path.Name + "-> " + r.Item1.Path.Name).Aggregate((a, b) => a + ", " + b)}");
                };

                Func <string> formatWatchingAddresses = () =>
                {
                    if (!_watchingAddresses.Any())
                    {
                        return("");
                    }
                    return(string.Join(",", WatchingAddresses));
                };

                return($"Stats(watching={_watching}, watchingNodes={_watchingNodes}, watchingRefs=[{formatWatchingRefs()}], watchingAddresses=[{formatWatchingAddresses()}])");
            }
Ejemplo n.º 16
0
        /// <summary>
        /// Add a new word into this set
        /// </summary>
        /// <param name="word">The word to add into the set.</param>
        /// <returns>A new vocabulary set that includes this word.</returns>
        public VocabularySet Add(VocabularyWord word)
        {
            if (word == null)
            {
                throw new ArgumentNullException(nameof(word));
            }

            if (_words.Contains(word))
            {
                return(this);
            }

            if (_words.Any(w => w.HasSpelling(word.Spelling)))
            {
                throw new ArgumentException(
                          $"A word with spelling {word.Spelling} already exists in this set.",
                          nameof(word));
            }

            var words = _words.Add(word);

            return(new VocabularySet(this, words: words));
        }
Ejemplo n.º 17
0
 public bool IsIncluded(Key key)
 {
     return(_keys.Any(x => x.IsIncluded(key)));
 }
Ejemplo n.º 18
0
        public static void RecursiveCopy(
            DirectoryInfo sourceDirectoryInfo,
            DirectoryInfo targetDirectoryInfo,
            [NotNull] ILogger logger,
            ImmutableArray <string> excludedFilePatterns)
        {
            if (sourceDirectoryInfo == null)
            {
                throw new ArgumentNullException(nameof(sourceDirectoryInfo));
            }

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

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

            sourceDirectoryInfo.Refresh();
            targetDirectoryInfo.Refresh();

            if (!targetDirectoryInfo.Exists)
            {
                logger.Verbose("Creating directory '{FullName}'", targetDirectoryInfo.FullName);
                targetDirectoryInfo.Create();
            }

            ImmutableArray <FileInfo> deniedFilesInDirectory = excludedFilePatterns
                                                               .Select(sourceDirectoryInfo.GetFiles).SelectMany(files => files)
                                                               .ToImmutableArray();

            foreach (FileInfo currentFile in sourceDirectoryInfo.GetFiles())
            {
                if (_DeniedExtensions.Any(denied =>
                                          currentFile.Extension.Length > 0 &&
                                          denied.Equals(currentFile.Extension, StringComparison.OrdinalIgnoreCase)))
                {
                    logger.Verbose("Skipping denied file '{FullName}' due to its file extension",
                                   currentFile.FullName);
                    continue;
                }

                if (deniedFilesInDirectory.Any(file =>
                                               file.FullName.Equals(currentFile.FullName, StringComparison.OrdinalIgnoreCase)))
                {
                    logger.Verbose("Skipping denied file '{FullName}' due to its file pattern {Patterns}",
                                   currentFile.FullName,
                                   excludedFilePatterns);
                    continue;
                }

                var targetFile = new FileInfo(Path.Combine(targetDirectoryInfo.FullName, currentFile.Name));
                logger.Verbose("Copying file '{FullName}' to '{FullName1}'", currentFile.FullName, targetFile.FullName);
                currentFile.CopyTo(targetFile.FullName, true);
            }

            foreach (DirectoryInfo subDirectory in sourceDirectoryInfo.GetDirectories())
            {
                var targetSubDirectory = new DirectoryInfo(
                    Path.Combine(targetDirectoryInfo.FullName, subDirectory.Name));

                RecursiveCopy(subDirectory, targetSubDirectory, logger, excludedFilePatterns);
            }
        }
        protected virtual DependenciesChange ProcessDependenciesChanges(
            IProjectSubscriptionUpdate projectSubscriptionUpdate,
            IProjectCatalogSnapshot catalogs)
        {
            var changes = projectSubscriptionUpdate.ProjectChanges;
            var resolvedReferenceChanges =
                ResolvedReferenceRuleNames.Where(x => changes.Keys.Contains(x))
                .Select(ruleName => changes[ruleName]).ToImmutableHashSet();

            var unresolvedReferenceSnapshots = changes.Values
                                               .Where(cd => !ResolvedReferenceRuleNames.Any(ruleName =>
                                                                                            string.Equals(ruleName,
                                                                                                          cd.After.RuleName,
                                                                                                          StringComparison.OrdinalIgnoreCase)))
                                               .ToDictionary(d => d.After.RuleName, d => d, StringComparer.OrdinalIgnoreCase);

            var rootTreeNodes      = new HashSet <IDependencyNode>(RootNode.Children);
            var dependenciesChange = new DependenciesChange();

            foreach (var unresolvedChange in unresolvedReferenceSnapshots.Values)
            {
                if (!unresolvedChange.Difference.AnyChanges)
                {
                    continue;
                }

                var itemType = GetItemTypeFromRuleName(unresolvedChange.After.RuleName,
                                                       catalogs,
                                                       true);
                if (itemType == null)
                {
                    // We must be missing that rule. Skip it.
                    continue;
                }

                foreach (string removedItemSpec in unresolvedChange.Difference.RemovedItems)
                {
                    var node = rootTreeNodes.FindNode(removedItemSpec, itemType);
                    if (node != null)
                    {
                        dependenciesChange.RemovedNodes.Add(node);
                    }
                }

                foreach (string addedItemSpec in unresolvedChange.Difference.AddedItems)
                {
                    var node = rootTreeNodes.FindNode(addedItemSpec, itemType);
                    if (node == null)
                    {
                        var properties = GetProjectItemProperties(unresolvedChange.After, addedItemSpec);
                        node = CreateDependencyNode(addedItemSpec,
                                                    itemType,
                                                    properties: properties,
                                                    resolved: false);
                        dependenciesChange.AddedNodes.Add(node);
                    }
                }
            }

            var updatedUnresolvedSnapshots = unresolvedReferenceSnapshots.Values.Select(cd => cd.After);

            foreach (var resolvedReferenceRuleChanges in resolvedReferenceChanges)
            {
                if (!resolvedReferenceRuleChanges.Difference.AnyChanges)
                {
                    continue;
                }

                // if resolved reference appears in Removed list, it means that it is either removed from
                // project or can not be resolved anymore. In case when it can not be resolved,
                // we must remove old "resolved" node and add new unresolved node with corresponding
                // properties changes (rules, icon, etc)
                // Note: removed resolved node is not added to "added unresolved diff", which we process
                // above, thus we need to do this properties update here. It is just cleaner to re-add node
                // instead of modifying properties.
                foreach (string removedItemSpec in resolvedReferenceRuleChanges.Difference.RemovedItems)
                {
                    string unresolvedItemSpec = resolvedReferenceRuleChanges.Before
                                                .Items[removedItemSpec][OriginalItemSpecPropertyName];
                    IProjectRuleSnapshot unresolvedReferenceSnapshot = null;
                    string unresolvedItemType = GetUnresolvedReferenceItemType(unresolvedItemSpec,
                                                                               updatedUnresolvedSnapshots,
                                                                               catalogs,
                                                                               out unresolvedReferenceSnapshot);
                    var node = rootTreeNodes.FindNode(removedItemSpec, unresolvedItemType);
                    if (node != null)
                    {
                        dependenciesChange.RemovedNodes.Add(node);

                        IImmutableDictionary <string, string> properties = null;
                        if (unresolvedReferenceSnapshot != null)
                        {
                            properties = GetProjectItemProperties(unresolvedReferenceSnapshot, unresolvedItemSpec);
                        }

                        node = CreateDependencyNode(unresolvedItemSpec,
                                                    unresolvedItemType,
                                                    properties: properties,
                                                    resolved: false);
                        dependenciesChange.AddedNodes.Add(node);
                    }
                }

                foreach (string addedItemSpec in resolvedReferenceRuleChanges.Difference.AddedItems)
                {
                    var properties = GetProjectItemProperties(resolvedReferenceRuleChanges.After, addedItemSpec);
                    if (properties == null || !properties.Keys.Contains(OriginalItemSpecPropertyName))
                    {
                        // if there no OriginalItemSpec, we can not associate item with the rule
                        continue;
                    }

                    var originalItemSpec = properties[OriginalItemSpecPropertyName];
                    IProjectRuleSnapshot unresolvedReferenceSnapshot = null;
                    var itemType = GetUnresolvedReferenceItemType(originalItemSpec,
                                                                  updatedUnresolvedSnapshots,
                                                                  catalogs,
                                                                  out unresolvedReferenceSnapshot);
                    if (string.IsNullOrEmpty(itemType))
                    {
                        // Note: design time build resolves not only our unresolved assemblies, but also
                        // all transitive assembly dependencies, which ar enot direct references and
                        // we should not show them. If reference does not have an unresolved reference
                        // corresponded to it, i.e. itemType = null here - we skip it.
                        continue;
                    }

                    // avoid adding unresolved dependency along with resolved one
                    var existingUnresolvedNode = dependenciesChange.AddedNodes.FindNode(originalItemSpec, itemType);
                    if (existingUnresolvedNode != null)
                    {
                        dependenciesChange.AddedNodes.Remove(existingUnresolvedNode);
                    }

                    // if unresolved dependency was added earlier, remove it, since it will be substituted by resolved one
                    existingUnresolvedNode = rootTreeNodes.FindNode(originalItemSpec, itemType);
                    if (existingUnresolvedNode != null)
                    {
                        dependenciesChange.RemovedNodes.Add(existingUnresolvedNode);
                    }

                    var newNode = CreateDependencyNode(originalItemSpec,
                                                       itemType: itemType,
                                                       properties: properties);
                    dependenciesChange.AddedNodes.Add(newNode);
                }
            }

            return(dependenciesChange);
        }
Ejemplo n.º 20
0
 private bool AlreadySeen(VClock version) => localVersion >= version || pendingDelivery.Any(x => x.Versioned.Version == version);
 private static bool HasCallerInformationAttribute(IParameterSymbol parameter, ImmutableHashSet <INamedTypeSymbol> callerAttributes)
 => parameter.GetAttributes().Any(
     attribute => callerAttributes.Any(
         callerAttribute => SymbolEqualityComparer.Default.Equals(callerAttribute, attribute.AttributeClass)));