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
        /// <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)
        {
            if (string.IsNullOrWhiteSpace(packageId))
            {
                throw new ArgumentNullException(nameof(packageId));
            }

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

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

            return(package);
        }
示例#3
0
        private async Task EnsureNuGetAndVsProjectAdapterCacheAsync()
        {
            await _initLock.ExecuteNuGetOperationAsync(async() =>
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (!_cacheInitialized && await IsSolutionOpenAsync())
                {
                    try
                    {
                        var dte = await _asyncServiceProvider.GetDTEAsync();

                        var supportedProjects = new List <Project>();
                        foreach (Project project in await EnvDTESolutionUtility.GetAllEnvDTEProjectsAsync(dte))
                        {
                            if (await EnvDTEProjectUtility.IsSupportedAsync(project))
                            {
                                supportedProjects.Add(project);
                            }
                        }

                        foreach (var project in supportedProjects)
                        {
                            try
                            {
                                var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(project);
                                await AddVsProjectAdapterToCacheAsync(vsProjectAdapter);
                            }
                            catch (Exception e)
                            {
                                // Ignore failed projects.
                                _logger.LogWarning($"The project {project.Name} failed to initialize as a NuGet project.");
                                _logger.LogError(e.ToString());
                            }

                            // Consider that the cache is initialized only when there are any projects to add.
                            _cacheInitialized = true;
                        }

                        await SetDefaultProjectNameAsync();
                    }
                    catch
                    {
                        _projectSystemCache.Clear();
                        _cacheInitialized       = false;
                        DefaultNuGetProjectName = null;

                        throw;
                    }
                }
            }, CancellationToken.None);
        }
示例#4
0
 private static void RegisterGlobalExceptionHandler(Common.ILogger logger)
 {
     AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
     {
         logger.LogError((Exception)e.ExceptionObject);
     };
 }
示例#5
0
 private void LogError(Task task)
 {
     foreach (var ex in task.Exception.Flatten().InnerExceptions)
     {
         _logger.LogError(ex.ToString());
     }
 }
        public async Task <bool> DoesNuGetSupportsAnyProjectAsync()
        {
            // Do NOT initialize VSSolutionManager through this API (by calling EnsureInitializeAsync)
            // This is a fast check implemented specifically for right click context menu to be
            // quick and does not involve initializing VSSolutionManager. Otherwise it will create
            // hang issues for right click on solution.
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            // first check with DTE, and if we find any supported project, then return immediately.
            var dte = _serviceProvider.GetDTE();

            var isSupported = EnvDTESolutionUtility.GetAllEnvDTEProjects(dte)
                              .Where(EnvDTEProjectUtility.IsSupported)
                              .Any();

            if (isSupported)
            {
                return(true);
            }

            var deferredProjects = await GetDeferredProjectsAsync();

            foreach (var project in deferredProjects)
            {
                try
                {
                    var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForDeferredProjectAsync(project);

                    if (vsProjectAdapter.IsSupported)
                    {
                        // as soon as we find a supported project, we returns without checking for all the projects.
                        return(true);
                    }
                }
                catch (Exception e)
                {
                    // Ignore failed projects.
                    _logger.LogWarning($"The project {project} failed to initialize as a NuGet project.");
                    _logger.LogError(e.ToString());
                }
            }

            return(false);
        }
示例#7
0
        /// <summary>
        /// Tries to create an instance of <see cref="NuGetProject"/> by calling registered
        /// providers in predefined order.
        /// </summary>
        /// <param name="vsProjectAdapter">A project adapter.</param>
        /// <param name="context">Project context</param>
        /// <param name="result">New project instance when <code>true</code> is returned.
        /// Otherwise - <code>null</code>.</param>
        /// <returns><code>true</code> when new project instance has been successfully created.</returns>
        public bool TryCreateNuGetProject(
            IVsProjectAdapter vsProjectAdapter,
            ProjectProviderContext context,
            out NuGetProject result)
        {
            Assumes.Present(vsProjectAdapter);
            Assumes.Present(context);

            _threadingService.ThrowIfNotOnUIThread();

            var exceptions = new List <Exception>();

            result = _providers
                     .Select(p =>
            {
                try
                {
                    if (p.TryCreateNuGetProject(
                            vsProjectAdapter,
                            context,
                            forceProjectType: false,
                            result: out var nuGetProject))
                    {
                        return(nuGetProject);
                    }
                }
                catch (Exception e)
                {
                    // Ignore failures. If this method returns null, the problem falls
                    // into one of the other NuGet project types.
                    exceptions.Add(e);
                }

                return(null);
            })
                     .FirstOrDefault(p => p != null);

            if (result == null)
            {
                exceptions.ForEach(e => _logger.LogError(e.ToString()));
            }

            return(result != null);
        }
        /// <summary>
        /// Tries to create an instance of <see cref="NuGetProject"/> by calling registered
        /// providers in predefined order.
        /// </summary>
        /// <param name="vsProjectAdapter">A project adapter.</param>
        /// <param name="context">Project context</param>
        /// <param name="result">New project instance when <code>true</code> is returned.
        /// Otherwise - <code>null</code>.</param>
        /// <returns><code>true</code> when new project instance has been successfully created.</returns>
        public async Task <NuGetProject> TryCreateNuGetProjectAsync(
            IVsProjectAdapter vsProjectAdapter,
            ProjectProviderContext context)
        {
            Assumes.Present(vsProjectAdapter);
            Assumes.Present(context);

            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (vsProjectAdapter.VsHierarchy != null &&
                VsHierarchyUtility.IsCPSCapabilityComplaint(vsProjectAdapter.VsHierarchy))
            {
                // Lazy load the CPS enabled JoinableTaskFactory for the UI.
                NuGetUIThreadHelper.SetJoinableTaskFactoryFromService(ProjectServiceAccessor.Value as IProjectServiceAccessor);
            }

            var exceptions = new List <Exception>();

            foreach (var provider in _providers)
            {
                try
                {
                    var nuGetProject = await provider.TryCreateNuGetProjectAsync(
                        vsProjectAdapter,
                        context,
                        forceProjectType : false);

                    if (nuGetProject != null)
                    {
                        return(nuGetProject);
                    }
                }
                catch (Exception e)
                {
                    // Ignore failures. If this method returns null, the problem falls
                    // into one of the other NuGet project types.
                    exceptions.Add(e);
                }
            }

            exceptions.ForEach(e => _logger.LogError(e.ToString()));

            return(null);
        }
        /// <param name="uri">The uri of a web resource for which credentials are needed.</param>
        /// <param name="proxy">Ignored.  Proxy information will not be passed to plugins.</param>
        /// <param name="type">
        /// The type of credential request that is being made. Note that this implementation of
        /// <see cref="ICredentialProvider"/> does not support providing proxy credenitials and treats
        /// all other types the same.
        /// </param>
        /// <param name="isRetry">If true, credentials were previously supplied by this
        /// provider for the same uri.</param>
        /// <param name="message">A message provided by NuGet to show to the user when prompting.</param>
        /// <param name="nonInteractive">If true, the plugin must not prompt for credentials.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A credential object.</returns>
        public async Task <CredentialResponse> GetAsync(Uri uri, IWebProxy proxy, CredentialRequestType type, string message, bool isRetry, bool nonInteractive, CancellationToken cancellationToken)
        {
            CredentialResponse taskResponse = null;

            if (type == CredentialRequestType.Proxy || !_isAnAuthenticationPlugin)
            {
                taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
                return(taskResponse);
            }

            var plugin = await _pluginManager.CreateSourceAgnosticPluginAsync(_discoveredPlugin, cancellationToken);

            if (!string.IsNullOrEmpty(plugin.Message))
            {
                // There is a potential here for double logging as the CredentialService itself catches the exceptions and tries to log it.
                // In reality the logger in the Credential Service will be null because the first request always comes from a resource provider (ServiceIndex provider)
                _logger.LogError(plugin.Message);
                throw new PluginException(plugin.Message); // Throwing here will block authentication and ensure that the complete operation fails
            }

            _isAnAuthenticationPlugin = plugin.Claims.Contains(OperationClaim.Authentication);

            if (_isAnAuthenticationPlugin)
            {
                AddOrUpdateLogger(plugin.Plugin);
                await SetPluginLogLevelAsync(plugin, _logger, cancellationToken);

                if (proxy != null)
                {
                    await SetProxyCredentialsToPlugin(uri, proxy, plugin, cancellationToken);
                }

                var request            = new GetAuthenticationCredentialsRequest(uri, isRetry, nonInteractive);
                var credentialResponse = await plugin.Plugin.Connection.SendRequestAndReceiveResponseAsync <GetAuthenticationCredentialsRequest, GetAuthenticationCredentialsResponse>(
                    MessageMethod.GetAuthenticationCredentials,
                    request,
                    cancellationToken);

                if (credentialResponse.ResponseCode == MessageResponseCode.NotFound && nonInteractive)
                {
                    _logger.LogWarning(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.SecurePluginWarning_UseInteractiveOption)
                        );
                }

                taskResponse = GetAuthenticationCredentialsResponseToCredentialResponse(credentialResponse);
            }
            else
            {
                taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
            }

            return(taskResponse);
        }
        /// <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);
        }
示例#11
0
        private void EnsureNuGetAndEnvDTEProjectCache()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!_cacheInitialized && IsSolutionOpen)
            {
                try
                {
                    var dte = _serviceProvider.GetDTE();
                    var supportedProjects = EnvDTESolutionUtility.GetAllEnvDTEProjects(dte)
                                            .Where(project => EnvDTEProjectUtility.IsSupported(project));

                    foreach (var project in supportedProjects)
                    {
                        try
                        {
                            AddEnvDTEProjectToCache(project);
                        }
                        catch (Exception e)
                        {
                            // Ignore failed projects.
                            _logger.LogWarning($"The project {project.Name} failed to initialize as a NuGet project.");
                            _logger.LogError(e.ToString());
                        }

                        // Consider that the cache is initialized only when there are any projects to add.
                        _cacheInitialized = true;
                    }

                    SetDefaultProjectName();
                }
                catch
                {
                    _projectSystemCache.Clear();
                    _cacheInitialized       = false;
                    DefaultNuGetProjectName = null;

                    throw;
                }
            }
        }
        /// <summary>
        /// Get the global property from the IBuildEngine API.
        /// </summary>
        /// <returns>Returns the dictionary with the global properties if they can be accessed. <see langword="null"/> otherwise, which means that the msbuild version doesn't implement this API. </returns>
        internal IReadOnlyDictionary <string, string> GetGlobalProperties(Common.ILogger logger)
        {
#if IS_CORECLR
            // MSBuild 16.5 and above has a method to get the global properties, older versions do not
            IReadOnlyDictionary <string, string> msBuildGlobalProperties = BuildEngine is IBuildEngine6 buildEngine6
                ? buildEngine6.GetGlobalProperties()
                : null;
#else
            IReadOnlyDictionary <string, string> msBuildGlobalProperties = null;

            // MSBuild 16.5 added a new interface, IBuildEngine6, which has a GetGlobalProperties() method.  However, we compile against
            // Microsoft.Build.Framework version 4.0 when targeting .NET Framework, so reflection is required since type checking
            // can't be done at compile time

            var getGlobalPropertiesMethod = BuildEngine.GetType().GetMethod("GetGlobalProperties", BindingFlags.Instance | BindingFlags.Public);

            if (getGlobalPropertiesMethod != null)
            {
                try
                {
                    if (getGlobalPropertiesMethod.Invoke(BuildEngine, null) is IReadOnlyDictionary <string, string> globalProperties)
                    {
                        msBuildGlobalProperties = globalProperties;
                    }
                }
                catch (Exception e)
                {
                    // This is an unexpected error, so we don't localize.
                    logger.LogError($"Internal Error. Failed calling the Microsoft.Build.Framework.IBuildEngine6.GetGlobalProperties method via reflection. Unable to determine the global properties.{e}");
                }
            }
            else
            {
                // This is an unexpected error, so we don't localize.
                logger.LogError($"Internal Error. Failed calling the Microsoft.Build.Framework.IBuildEngine6.GetGlobalProperties method via reflection. Unable to determine the global properties.");
            }
#endif
            return(msBuildGlobalProperties);
        }
示例#13
0
        /// <summary>
        /// Tries to create an instance of <see cref="NuGetProject"/> by calling registered
        /// providers in predefined order.
        /// </summary>
        /// <param name="vsProjectAdapter">A project adapter.</param>
        /// <param name="context">Project context</param>
        /// <param name="result">New project instance when <code>true</code> is returned.
        /// Otherwise - <code>null</code>.</param>
        /// <returns><code>true</code> when new project instance has been successfully created.</returns>
        public async Task <NuGetProject> TryCreateNuGetProjectAsync(
            IVsProjectAdapter vsProjectAdapter,
            ProjectProviderContext context)
        {
            Assumes.Present(vsProjectAdapter);
            Assumes.Present(context);

            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var exceptions = new List <Exception>();

            foreach (var provider in _providers)
            {
                try
                {
                    var nuGetProject = await provider.TryCreateNuGetProjectAsync(
                        vsProjectAdapter,
                        context,
                        forceProjectType : false);

                    if (nuGetProject != null)
                    {
                        return(nuGetProject);
                    }
                }
                catch (Exception e)
                {
                    // Ignore failures. If this method returns null, the problem falls
                    // into one of the other NuGet project types.
                    exceptions.Add(e);
                }
            }

            exceptions.ForEach(e => _logger.LogError(e.ToString()));

            return(null);
        }
示例#14
0
        private int LibraryDetail(PackageSpec project, LockFile lockfile, string targetName, string library)
        {
            var lib = lockfile.Libraries.FirstOrDefault(l => l.Name.Equals(library, StringComparison.OrdinalIgnoreCase));

            if (lib == null)
            {
                _log.LogError($"Library not found: {library}");
                return(-1);
            }

            _log.LogMinimal($"{lib.Name} {lib.Version}");
            _log.LogMinimal($"Servicable: {lib.IsServiceable}");
            _log.LogMinimal($"SHA512 Hash: {lib.Sha512}");
            _log.LogMinimal($"Files:");
            foreach (var file in lib.Files)
            {
                _log.LogMinimal($" * {file}");
            }

            IEnumerable <LockFileTarget> targets = lockfile.Targets;

            if (!string.IsNullOrEmpty(targetName))
            {
                var parts = targetName.Split('/');
                var tfm   = NuGetFramework.Parse(parts[0]);
                var rid   = parts[1];
                targets = targets.Where(t => string.Equals(rid, t.RuntimeIdentifier, StringComparison.Ordinal) && tfm.Equals(t.TargetFramework));
            }
            var libraryTargets = targets.Select(t => new { Target = t, Library = t.Libraries.FirstOrDefault(l => string.Equals(l.Name, library, StringComparison.OrdinalIgnoreCase)) });

            foreach (var libraryTarget in libraryTargets)
            {
                _log.LogMinimal($"Target: {libraryTarget.Target.TargetFramework}/{libraryTarget.Target.RuntimeIdentifier}");
                if (libraryTarget.Library == null)
                {
                    _log.LogMinimal(" Not supported");
                }
                else
                {
                    WriteList(Compile, libraryTarget.Library.CompileTimeAssemblies.Select(f => f.Path));
                    WriteList(Runtime, libraryTarget.Library.RuntimeAssemblies.Select(f => f.Path));
                    WriteList(Native, libraryTarget.Library.NativeLibraries.Select(f => f.Path));
                    WriteList(Framework, libraryTarget.Library.FrameworkAssemblies);
                    WriteList(FrameworkReference, libraryTarget.Library.FrameworkReferences);
                }
            }

            return(0);
        }
        private static IEnumerable <Packaging.PackageReference> GetInstalledPackageReferences(string projectConfigFilePath, bool allowDuplicatePackageIds, Common.ILogger log)
        {
            if (File.Exists(projectConfigFilePath))
            {
                try
                {
                    var xDocument = XDocument.Load(projectConfigFilePath);
                    var reader    = new PackagesConfigReader(xDocument);
                    return(reader.GetPackages(allowDuplicatePackageIds));
                }
                catch (XmlException ex)
                {
                    var message = string.Format(
                        Strings.Error_PackagesConfigParseError,
                        projectConfigFilePath,
                        ex.Message);

                    log.LogError(message);
                }
            }

            return(Enumerable.Empty <Packaging.PackageReference>());
        }
示例#16
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;
            }
        }
 private void LogError(Exception exception)
 {
     _logger.LogError(ExceptionUtilities.DisplayMessage(exception));
 }
示例#18
0
        private async Task EnsureNuGetAndVsProjectAdapterCacheAsync()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!_cacheInitialized && IsSolutionOpen)
            {
                try
                {
                    var deferedProjects = GetDeferredProjects();

                    foreach (var project in deferedProjects)
                    {
                        try
                        {
                            var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForDeferredProjectAsync(project);

                            AddVsProjectAdapterToCache(vsProjectAdapter);
                        }
                        catch (Exception e)
                        {
                            // Ignore failed projects.
                            _logger.LogWarning($"The project {project} failed to initialize as a NuGet project.");
                            _logger.LogError(e.ToString());
                        }

                        // Consider that the cache is initialized only when there are any projects to add.
                        _cacheInitialized = true;
                    }

                    var dte = _serviceProvider.GetDTE();

                    var supportedProjects = EnvDTESolutionUtility
                                            .GetAllEnvDTEProjects(dte)
                                            .Where(EnvDTEProjectUtility.IsSupported);

                    foreach (var project in supportedProjects)
                    {
                        try
                        {
                            var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(project);

                            AddVsProjectAdapterToCache(vsProjectAdapter);
                        }
                        catch (Exception e)
                        {
                            // Ignore failed projects.
                            _logger.LogWarning($"The project {project.Name} failed to initialize as a NuGet project.");
                            _logger.LogError(e.ToString());
                        }

                        // Consider that the cache is initialized only when there are any projects to add.
                        _cacheInitialized = true;
                    }

                    SetDefaultProjectName();
                }
                catch
                {
                    _projectSystemCache.Clear();
                    _cacheInitialized       = false;
                    DefaultNuGetProjectName = null;

                    throw;
                }
            }
        }