public void Log(ProjectManagement.MessageLevel level, string message, params object[] args)
        {
            if (args.Length > 0)
            {
                message = string.Format(CultureInfo.CurrentCulture, message, args);
            }

            switch (level)
            {
            case ProjectManagement.MessageLevel.Debug:
                _logger.LogDebug(message);
                break;

            case ProjectManagement.MessageLevel.Info:
                _logger.LogMinimal(message);
                break;

            case ProjectManagement.MessageLevel.Warning:
                _logger.LogWarning(message);
                break;

            case ProjectManagement.MessageLevel.Error:
                _logger.LogError(message);
                break;
            }
        }
예제 #2
0
        internal /* for testing */ static bool ShouldMergeAnalysisSettings(string language, AnalysisConfig config, Common.ILogger logger)
        {
            Debug.Assert(!string.IsNullOrEmpty(language));
            Debug.Assert(config != null);

            // See https://github.com/SonarSource/sonar-scanner-msbuild/issues/561
            // Legacy behaviour is to overwrite.
            // The new (SQ 7.4+) behaviour is to merge only if sonar.[LANGUAGE].roslyn.ignoreIssues is false.
            var serverVersion = config?.FindServerVersion();

            if (serverVersion == null || serverVersion < new Version("7.4"))
            {
                logger.LogInfo(Resources.AnalyzerSettings_ExternalIssueNotSupported, SonarProduct.GetSonarProductToLog(config?.SonarQubeHostUrl));
                return(false);
            }

            var settingName   = $"sonar.{language}.roslyn.ignoreIssues";
            var settingInFile = config.GetSettingOrDefault(settingName, includeServerSettings: true, defaultValue: "false");

            if (bool.TryParse(settingInFile, out var ignoreExternalRoslynIssues))
            {
                logger.LogDebug(Resources.AnalyzerSettings_ImportAllSettingValue, settingName, ignoreExternalRoslynIssues.ToString().ToLowerInvariant());
                return(!ignoreExternalRoslynIssues);
            }
            else
            {
                logger.LogWarning(Resources.AnalyzerSettings_InvalidValueForImportAll, settingName, settingInFile);
                return(false);
            }
        }
        public async Task <IEnumerable <ProjectRestoreReference> > GetProjectReferencesAsync(
            Common.ILogger logger, CancellationToken _)
        {
            var results = new List <ProjectRestoreReference>();

            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var vcProject = await _vcProject.GetValueAsync();

            var  references           = vcProject.VCReferences as VCReferences;
            var  projectReferences    = references.GetReferencesOfType((uint)vcRefType.VCRT_PROJECT);
            bool hasMissingReferences = false;

            foreach (var reference in projectReferences)
            {
                try
                {
                    var vcReference = reference as VCProjectReference;
                    if (vcReference.UseInBuild)
                    {
                        if (vcReference.ReferencedProject != null)
                        {
                            var referencedProject       = vcReference.ReferencedProject as Project;
                            var childProjectPath        = referencedProject.FileName;
                            var projectRestoreReference = new ProjectRestoreReference()
                            {
                                ProjectPath       = childProjectPath,
                                ProjectUniqueName = childProjectPath
                            };

                            results.Add(projectRestoreReference);
                        }
                        else
                        {
                            hasMissingReferences = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    hasMissingReferences = true;

                    logger.LogDebug(ex.ToString());
                }
            }

            if (hasMissingReferences)
            {
                // Log a generic message once per project if any items could not be resolved.
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.UnresolvedItemDuringProjectClosureWalk,
                    _vsProjectAdapter.UniqueName);

                logger.LogVerbose(message);
            }

            return(results);
        }
        /// <summary>
        /// Attempts to download a NuGet package with the specified id and optional version
        /// to the specified directory
        /// </summary>
        public IPackage FetchPackage(string packageId, SemanticVersion version, string localNuGetPath)
        {
            if (string.IsNullOrWhiteSpace(packageId))
            {
                throw new ArgumentNullException("packageId");
            }
            if (string.IsNullOrWhiteSpace(localNuGetPath))
            {
                throw new ArgumentNullException("localNuGetPath");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            logger.LogDebug(UIResources.NG_CreatingRepository, this.packageSource);
            IPackageRepository repository = PackageRepositoryFactory.Default.CreateRepository(packageSource);

            IPackage package = TryGetPackage(repository, packageId, version);

            if (package != null)
            {
                Directory.CreateDirectory(localNuGetPath);

                IPackageManager manager = new PackageManager(repository, localNuGetPath);
                manager.Logger = new NuGetLoggerAdapter(this.logger);

                try
                {
                    // Prerelease packages enabled by default
                    manager.InstallPackage(package, false, true, false);
                }
                catch (InvalidOperationException e)
                {
                    logger.LogError(UIResources.NG_ERROR_PackageInstallFail, e.Message);
                    return(null);
                }
            }

            return(package);
        }
        /// <summary>
        /// Creates credential providers for each valid plugin (regardless if it supports authentication or not)
        /// </summary>
        /// <returns>credential providers</returns>
        public async Task <IEnumerable <ICredentialProvider> > BuildAll()
        {
            var availablePlugins = await _pluginManager.FindAvailablePluginsAsync(CancellationToken.None);

            var plugins = new List <ICredentialProvider>();

            foreach (var pluginDiscoveryResult in availablePlugins)
            {
                if (pluginDiscoveryResult.PluginFile.State == PluginFileState.Valid)
                {
                    _logger.LogDebug($"Will attempt to use {pluginDiscoveryResult.PluginFile.Path} as a credential provider");
                    plugins.Add(new SecurePluginCredentialProvider(_pluginManager, pluginDiscoveryResult, _logger));
                }
                else
                {
                    _logger.LogDebug($"Skipping {pluginDiscoveryResult.PluginFile.Path} as a credential provider.\n{pluginDiscoveryResult.Message}");
                }
            }

            return(plugins);
        }
        public async Task <IEnumerable <ProjectRestoreReference> > GetProjectReferencesAsync(
            Common.ILogger logger, CancellationToken _)
        {
            var unconfiguredProject = await _unconfiguredProject.GetValueAsync();

            IBuildDependencyProjectReferencesService service = await GetProjectReferencesService(unconfiguredProject);

            if (service == null)
            {
                return(Enumerable.Empty <ProjectRestoreReference>());
            }

            var results = new List <ProjectRestoreReference>();
            var hasMissingReferences = false;

            foreach (IUnresolvedBuildDependencyProjectReference projectReference in await service.GetUnresolvedReferencesAsync())
            {
                try
                {
                    if (await projectReference.GetReferenceOutputAssemblyAsync())
                    {
                        string childProjectPath        = projectReference.EvaluatedIncludeAsFullPath;
                        var    projectRestoreReference = new ProjectRestoreReference()
                        {
                            ProjectPath       = childProjectPath,
                            ProjectUniqueName = childProjectPath
                        };

                        results.Add(projectRestoreReference);
                    }
                }
                catch (Exception ex)
                {
                    hasMissingReferences = true;
                    logger.LogDebug(ex.ToString());
                }
            }

            if (hasMissingReferences)
            {
                // Log a generic message once per project if any items could not be resolved.
                // In most cases this can be ignored, but in the rare case where the unresolved
                // item is actually a project the restore result will be incomplete.
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.UnresolvedItemDuringProjectClosureWalk,
                    _vsProjectAdapter.UniqueName);

                logger.LogVerbose(message);
            }

            return(results);
        }
        /// <summary>
        /// Creates and returns an aggregate repository using the specified settings
        /// </summary>
        public static IPackageRepository CreateRepository(ISettings settings, Common.ILogger logger)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            // Load the user and machine-wide settings
            logger.LogDebug(UIResources.NG_FetchingConfigFiles);

            // Get a package source provider that can use the settings
            PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings);

            logger.LogDebug(UIResources.NG_ListingEnablePackageSources);
            IEnumerable <PackageSource> enabledSources = packageSourceProvider.GetEnabledPackageSources();

            if (!enabledSources.Any())
            {
                logger.LogWarning(UIResources.NG_NoEnabledPackageSources);
            }
            else
            {
                foreach (PackageSource enabledSource in enabledSources)
                {
                    logger.LogDebug(UIResources.NG_ListEnabledPackageSource, enabledSource.Source, enabledSource.IsMachineWide);
                }
            }

            // Create an aggregate repository that uses all of the configured sources
            AggregateRepository aggRepo = packageSourceProvider.CreateAggregateRepository(PackageRepositoryFactory.Default,
                                                                                          true /* ignore failing repos. Errors will be logged as warnings. */);

            aggRepo.Logger = new NuGetLoggerAdapter(logger);

            return(aggRepo);
        }
예제 #8
0
        /// <summary>
        /// Creates credential providers for each valid plugin (regardless if it supports authentication or not)
        /// </summary>
        /// <returns>credential providers</returns>
        public async Task <IEnumerable <ICredentialProvider> > BuildAllAsync()
        {
            var availablePlugins = await _pluginManager.FindAvailablePluginsAsync(CancellationToken.None);

            var plugins = new List <ICredentialProvider>();

            foreach (var pluginDiscoveryResult in availablePlugins)
            {
                _logger.LogDebug(string.Format(CultureInfo.CurrentCulture, Resources.SecurePluginNotice_UsingPluginAsProvider, pluginDiscoveryResult.PluginFile.Path));
                plugins.Add(new SecurePluginCredentialProvider(_pluginManager, pluginDiscoveryResult, _canShowDialog, _logger));
            }

            return(plugins);
        }
예제 #9
0
        public void Log(MessageLevel level, string message, params object[] args)
        {
            // Add a prefix to the message to make it easier to determine the source
            string prefixedMessage = LogMessagePrefix + message;

            switch (level)
            {
            case MessageLevel.Debug:
                logger.LogDebug(prefixedMessage, args);
                break;

            case MessageLevel.Error:
                logger.LogError(prefixedMessage, args);
                break;

            case MessageLevel.Warning:
                logger.LogWarning(prefixedMessage, args);
                break;

            default:
                logger.LogInfo(prefixedMessage, args);
                break;
            }
        }
예제 #10
0
        private bool IsReferenceResolved(Reference3 reference, Common.ILogger logger)
        {
            _threadingService.ThrowIfNotOnUIThread();

            try
            {
                // Verify that this is a valid and resolved reference
                return(reference != null && reference.Resolved);
            }
            catch (Exception ex)
            {
                logger.LogDebug(ex.ToString());
            }

            return(false);
        }
예제 #11
0
        private bool IsProjectReference(Reference3 reference, Common.ILogger logger)
        {
            _threadingService.ThrowIfNotOnUIThread();

            try
            {
                // Verify that this is a project reference
                return(reference != null && reference.SourceProject != null);
            }
            catch (Exception ex)
            {
                logger.LogDebug(ex.ToString());
            }

            return(false);
        }
        /// <summary>
        /// Creates a NuGet repo depending on the given command line arguments for the customnugetrepo path.
        /// </summary>
        public static IPackageRepository CreateRepositoryForArguments(Common.ILogger logger, ProcessedArgs processedArgs, string defaultNuGetPath)
        {
            IPackageRepository repo;

            if (string.IsNullOrWhiteSpace(processedArgs.CustomNuGetRepository))
            {
                ISettings nuGetSettings = GetSettingsFromConfigFiles(defaultNuGetPath);
                repo = CreateRepository(nuGetSettings, logger);
            }
            else
            {
                logger.LogDebug(UIResources.NG_UsingCustomNuGetFolder, processedArgs.CustomNuGetRepository);
                repo = PackageRepositoryFactory.Default.CreateRepository(processedArgs.CustomNuGetRepository);
            }

            return(repo);
        }
        private void ListPackages(IList <IPackage> packages)
        {
            logger.LogDebug(UIResources.NG_NumberOfPackagesLocated, packages.Count);

            if (packages.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(UIResources.NG_PackageVersionListHeader);
                foreach (IPackage package in packages)
                {
                    sb.AppendFormat("  {0}", package.Version);
                    if (package.IsLatestVersion)
                    {
                        sb.AppendFormat(" {0}", UIResources.NG_IsLatestPackageVersionSuffix);
                    }

                    sb.AppendLine();
                }
                this.logger.LogDebug(sb.ToString());
            }
        }
예제 #14
0
        public async Task <IEnumerable <ProjectRestoreReference> > GetProjectReferencesAsync(
            Common.ILogger logger, CancellationToken _)
        {
            // DTE calls need to be done from the main thread
            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var results = new List <ProjectRestoreReference>();
            var hasMissingReferences = false;
            var hasProjectsWithUnresolvedMetadata = false;

            // find all references in the project
            foreach (var childReference in GetVSProjectReferences())
            {
                try
                {
                    var reference3 = childReference as Reference3;

                    // Verify that this is a project reference
                    if (IsProjectReference(reference3, logger))
                    {
                        // Verify that this is a valid and resolved project reference
                        if (!IsReferenceResolved(reference3, logger))
                        {
                            hasMissingReferences = true;
                            continue;
                        }

                        if (await EnvDTEProjectUtility.HasUnsupportedProjectCapabilityAsync(reference3.SourceProject))
                        {
                            // Skip this shared project
                            continue;
                        }

                        var childProjectPath = reference3.SourceProject.GetFullProjectPath();

                        // Skip projects which have ReferenceOutputAssembly=false
                        var addProject = true;

                        if (childReference is Reference6 reference6)
                        {
                            reference6.GetMetadata(_referenceMetadata, out Array _, out Array metadataValues);
                            var referenceOutputAssembly = GetReferenceMetadataValue(metadataValues);
                            addProject = string.IsNullOrEmpty(referenceOutputAssembly) ||
                                         !string.Equals(bool.FalseString, referenceOutputAssembly, StringComparison.OrdinalIgnoreCase);
                        }
                        else
                        {
                            hasProjectsWithUnresolvedMetadata = true;
                        }

                        if (addProject)
                        {
                            results.Add(new ProjectRestoreReference()
                            {
                                ProjectPath       = childProjectPath,
                                ProjectUniqueName = childProjectPath
                            });
                        }
                    }
                    else
                    {
                        hasMissingReferences = true;
                    }
                }
                catch (Exception ex)
                {
                    // Exceptions are expected in some scenarios for native projects,
                    // ignore them and show a warning
                    hasMissingReferences = true;

                    logger.LogDebug(ex.ToString());

                    Debug.Fail("Unable to find project dependencies: " + ex.ToString());
                }
            }

            if (hasMissingReferences)
            {
                // Log a generic message once per project if any items could not be resolved.
                // In most cases this can be ignored, but in the rare case where the unresolved
                // item is actually a project the restore result will be incomplete.
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.UnresolvedItemDuringProjectClosureWalk,
                    _vsProjectAdapter.UniqueName);

                logger.LogVerbose(message);
            }

            if (hasProjectsWithUnresolvedMetadata)
            {
                IList <string> excludedProjects = await GetExcludedProjectsAsync(logger);

                if (excludedProjects.Count > 0)
                {
                    results = results.Where(e => !excludedProjects.Contains(e.ProjectPath, StringComparer.OrdinalIgnoreCase)).ToList();
                }
            }

            return(results);
예제 #15
0
        public async Task <IEnumerable <ProjectRestoreReference> > GetProjectReferencesAsync(
            Common.ILogger logger, CancellationToken _)
        {
            // DTE calls need to be done from the main thread
            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var results = new List <ProjectRestoreReference>();

            var itemsFactory = ServiceLocator.GetInstance <IVsEnumHierarchyItemsFactory>();

            // Verify ReferenceOutputAssembly
            var excludedProjects     = GetExcludedReferences(itemsFactory, logger);
            var hasMissingReferences = false;

            // find all references in the project
            foreach (var childReference in GetVSProjectReferences())
            {
                try
                {
                    var reference3 = childReference as Reference3;

                    // Verify that this is a project reference
                    if (IsProjectReference(reference3, logger))
                    {
                        // Verify that this is a valid and resolved project reference
                        if (!IsReferenceResolved(reference3, logger))
                        {
                            hasMissingReferences = true;
                            continue;
                        }

                        if (EnvDTEProjectUtility.HasUnsupportedProjectCapability(reference3.SourceProject))
                        {
                            // Skip this shared project
                            continue;
                        }

                        var childProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(reference3.SourceProject);

                        // Skip projects which have ReferenceOutputAssembly=false
                        if (!string.IsNullOrEmpty(childProjectPath) &&
                            !excludedProjects.Contains(childProjectPath, StringComparer.OrdinalIgnoreCase))
                        {
                            var restoreReference = new ProjectRestoreReference()
                            {
                                ProjectPath       = childProjectPath,
                                ProjectUniqueName = childProjectPath
                            };

                            results.Add(restoreReference);
                        }
                    }
                    else
                    {
                        hasMissingReferences = true;
                    }
                }
                catch (Exception ex)
                {
                    // Exceptions are expected in some scenarios for native projects,
                    // ignore them and show a warning
                    hasMissingReferences = true;

                    logger.LogDebug(ex.ToString());

                    Debug.Fail("Unable to find project dependencies: " + ex.ToString());
                }
            }

            if (hasMissingReferences)
            {
                // Log a generic message once per project if any items could not be resolved.
                // In most cases this can be ignored, but in the rare case where the unresolved
                // item is actually a project the restore result will be incomplete.
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.UnresolvedItemDuringProjectClosureWalk,
                    _vsProjectAdapter.UniqueName);

                logger.LogVerbose(message);
            }

            return(results);
        }