예제 #1
0
        // Read the source's end point to get the index json.
        // An exception will be thrown on failure.
        private async Task <ServiceIndexResourceV3> GetServiceIndexResourceV3(
            SourceRepository source,
            DateTime utcNow,
            ILogger log,
            CancellationToken token)
        {
            var url = source.PackageSource.Source;
            var httpSourceResource = await source.GetResourceAsync <HttpSourceResource>(token);

            var client = httpSourceResource.HttpSource;

            const int maxRetries = 3;

            for (var retry = 1; retry <= maxRetries; retry++)
            {
                using (var sourceCacheContext = new SourceCacheContext())
                {
                    var cacheContext = HttpSourceCacheContext.Create(sourceCacheContext, isFirstAttempt: retry == 1);

                    try
                    {
                        return(await client.GetAsync(
                                   new HttpSourceCachedRequest(
                                       url,
                                       "service_index",
                                       cacheContext)
                        {
                            EnsureValidContents = stream => HttpStreamValidation.ValidateJObject(url, stream),
                            MaxTries = 1,
                            IsRetry = retry > 1,
                            IsLastAttempt = retry == maxRetries
                        },
                                   async httpSourceResult =>
                        {
                            var result = await ConsumeServiceIndexStreamAsync(httpSourceResult.Stream, utcNow, token);

                            return result;
                        },
                                   log,
                                   token));
                    }
                    catch (Exception ex) when(retry < maxRetries)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_RetryingServiceIndex, url)
                                      + Environment.NewLine
                                      + ExceptionUtilities.DisplayMessage(ex);

                        log.LogMinimal(message);
                    }
                    catch (Exception ex) when(retry == maxRetries)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_FailedToReadServiceIndex, url);

                        throw new FatalProtocolException(message, ex);
                    }
                }
            }

            return(null);
        }
예제 #2
0
        /// <summary>
        /// Async call for install a package by Id.
        /// </summary>
        /// <param name="identities"></param>
        private async Task InstallPackageByIdAsync()
        {
            try
            {
                await InstallPackageByIdAsync(Project, Id, ResolutionContext, this, WhatIf.IsPresent);
            }
            catch (FatalProtocolException ex)
            {
                _status = NuGetOperationStatus.Failed;

                // Additional information about the exception can be observed by using the -verbose switch with the install-package command
                Log(MessageLevel.Debug, ExceptionUtilities.DisplayMessage(ex));

                // Wrap FatalProtocolException coming from the server with a user friendly message
                var error = String.Format(CultureInfo.CurrentUICulture, Resources.Exception_PackageNotFound, Id, Source);
                Log(MessageLevel.Error, error);
            }
            catch (Exception ex)
            {
                _status = NuGetOperationStatus.Failed;
                Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
            finally
            {
                BlockingCollection.Add(new ExecutionCompleteMessage());
            }
        }
        protected void WaitAndLogPackageActions()
        {
            try {
                while (true)
                {
                    var message = BlockingCollection.Take();
                    if (message is ExecutionCompleteMessage)
                    {
                        break;
                    }

                    var scriptMessage = message as ScriptMessage;
                    if (scriptMessage != null)
                    {
                        ExecutePSScriptInternal(scriptMessage);
                        continue;
                    }

                    var logMessage = message as LogMessage;
                    if (logMessage != null)
                    {
                        LogCore(logMessage.Level, logMessage.Content);
                        continue;
                    }

                    //var flushMessage = message as FlushMessage;
                    //if (flushMessage != null) {
                    //	_flushSemaphore.Release ();
                    //}
                }
            } catch (InvalidOperationException ex) {
                LogCore(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
        }
        /// <summary>
        /// Async call for install packages from the list of identities.
        /// </summary>
        /// <param name="identities"></param>
        private async Task InstallPackagesAsync(IEnumerable <PackageIdentity> identities)
        {
            try
            {
                using (var sourceCacheContext = new SourceCacheContext())
                {
                    var resolutionContext = new ResolutionContext(
                        GetDependencyBehavior(),
                        _allowPrerelease,
                        false,
                        VersionConstraints.None,
                        new GatherCache(),
                        sourceCacheContext);

                    foreach (PackageIdentity identity in identities)
                    {
                        await InstallPackageByIdentityAsync(Project, identity, resolutionContext, this, WhatIf.IsPresent);
                    }
                }
            }
            catch (Exception ex)
            {
                // set nuget operation status to failed when an exception is thrown
                _status = NuGetOperationStatus.Failed;
                Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
            finally
            {
                BlockingCollection.Add(new ExecutionCompleteMessage());
            }
        }
예제 #5
0
        public void ShowError(Exception ex)
        {
            if (ex is NuGetResolverConstraintException ||
                ex is PackageAlreadyInstalledException ||
                ex is MinClientVersionException ||
                ex is FrameworkException ||
                ex is NuGetProtocolException ||
                ex is PackagingException ||
                ex is InvalidOperationException)
            {
                // for exceptions that are known to be normal error cases, just
                // display the message.
                ProjectContext.Log(MessageLevel.Info, ExceptionUtilities.DisplayMessage(ex, indent: true));

                // write to activity log
                var activityLogMessage = string.Format(CultureInfo.CurrentCulture, ex.ToString());
                ActivityLog.LogError(LogEntrySource, activityLogMessage);
            }
            else
            {
                ProjectContext.Log(MessageLevel.Error, ex.ToString());
            }

            UILogger.ReportError(ExceptionUtilities.DisplayMessage(ex, indent: false));
        }
예제 #6
0
        public void ShowError_WhenArgumentIsNotRemoteInvocationException_ShowsError()
        {
            var        exception     = new DivideByZeroException();
            var        defaultLogger = new Mock <INuGetUILogger>();
            var        projectLogger = new Mock <INuGetUILogger>();
            const bool indent        = false;

            defaultLogger.Setup(
                x => x.ReportError(
                    It.Is <ILogMessage>(
                        logMessage => logMessage.Level == LogLevel.Error &&
                        logMessage.Message == ExceptionUtilities.DisplayMessage(exception, indent))));
            projectLogger.Setup(
                x => x.Log(
                    It.Is <MessageLevel>(level => level == MessageLevel.Error),
                    It.Is <string>(message => message == exception.ToString())));

            using (NuGetUI ui = CreateNuGetUI(defaultLogger.Object, projectLogger.Object))
            {
                ui.ShowError(exception);

                defaultLogger.VerifyAll();
                projectLogger.VerifyAll();
            }
        }
예제 #7
0
        private async Task <NetworkCredential> PromptForProxyCredentialsAsync(Uri proxyAddress, IWebProxy proxy, ILogger log, CancellationToken cancellationToken)
        {
            ICredentials promptCredentials;

            try
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.Http_CredentialsForProxy,
                    proxyAddress);

                promptCredentials = await _credentialService.GetCredentialsAsync(
                    proxyAddress,
                    proxy,
                    type : CredentialRequestType.Proxy,
                    message : message,
                    cancellationToken : cancellationToken);
            }
            catch (OperationCanceledException)
            {
                throw; // pass-thru
            }
            catch (Exception e)
            {
                // Fatal credential service failure
                log.LogError(ExceptionUtilities.DisplayMessage(e));
                promptCredentials = null;
            }

            return(promptCredentials?.GetCredential(proxyAddress, BasicAuthenticationType));;
        }
        /// <summary>
        /// Update or reinstall all packages installed to a solution. For Update-Package or Update-Package -Reinstall.
        /// </summary>
        /// <returns></returns>
        private async Task UpdateOrReinstallAllPackagesAsync()
        {
            try
            {
                // if the source is explicitly specified we will use exclusively that source otherwise use ALL enabled sources
                var actions = await PackageManager.PreviewUpdatePackagesAsync(
                    Projects,
                    ResolutionContext,
                    this,
                    PrimarySourceRepositories,
                    PrimarySourceRepositories,
                    Token);

                if (!actions.Any())
                {
                    _status = NuGetOperationStatus.NoOp;
                }
                else
                {
                    _packageCount = actions.Select(action => action.PackageIdentity.Id).Distinct().Count();
                }

                await ExecuteActions(actions);
            }
            catch (Exception ex)
            {
                _status = NuGetOperationStatus.Failed;
                Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
            finally
            {
                BlockingCollection.Add(new ExecutionCompleteMessage());
            }
        }
        public void ExceptionUtilities_LeavesIndentAndWhitespaceInMessage()
        {
            /* Arrange
             * Exceptions:
             *  A - B
             */
            var b = new Exception($"B1{Environment.NewLine}  B2{Environment.NewLine}{Environment.NewLine}    B3");
            var a = new Exception("A", b);

            // Act
            var message = ExceptionUtilities.DisplayMessage(a);

            // Assert
            var actual   = GetLines(message);
            var expected = new[]
            {
                "A",
                "  B1",
                "    B2",
                "  ",
                "      B3"
            };

            Assert.Equal(expected, actual);
        }
예제 #10
0
        /// <summary>
        /// Get list of packages from the remote package source. Used for Get-Package -ListAvailable.
        /// </summary>
        /// <param name="searchString">The search string to use for filtering.</param>
        /// <param name="includePrerelease">Whether or not to include prerelease packages in the results.</param>
        /// <param name="handleError">
        /// An action for handling errors during the enumeration of the returned results. The
        /// parameter is the error message. This action is never called by multiple threads at once.
        /// </param>
        /// <returns>The lazy sequence of package search metadata.</returns>
        protected IEnumerable <IPackageSearchMetadata> GetPackagesFromRemoteSource(
            string searchString,
            bool includePrerelease,
            Action <string> handleError)
        {
            var searchFilter = new SearchFilter(includePrerelease: includePrerelease);

            searchFilter.IncludeDelisted = false;
            var packageFeed = new MultiSourcePackageFeed(PrimarySourceRepositories, logger: null);
            var searchTask  = packageFeed.SearchAsync(searchString, searchFilter, Token);

            return(PackageFeedEnumerator.Enumerate(
                       packageFeed,
                       searchTask,
                       (source, exception) =>
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.Cmdlet_FailedToSearchSource,
                    source,
                    Environment.NewLine,
                    ExceptionUtilities.DisplayMessage(exception));

                handleError(message);
            },
                       Token));
        }
        public void ExceptionUtilities_IgnoresDuplicateAdjacent()
        {
            /* Arrange
             * Exceptions:
             *  A -> A -> B -> B -> C -> B
             */
            var b3 = new Exception("B");
            var c0 = new Exception("C", b3);
            var b2 = new Exception("B", c0);
            var b1 = new Exception("B", b2);
            var b0 = new Exception("B", b1);
            var a1 = new Exception("A", b0);
            var a0 = new Exception("A", a1);

            // Act
            var message = ExceptionUtilities.DisplayMessage(a1);

            // Assert
            var actual   = GetLines(message);
            var expected = new[]
            {
                "A",
                "  B",
                "  C",
                "  B"
            };

            Assert.Equal(expected, actual);
        }
예제 #12
0
        /// <summary>
        /// Async call for sync package to the version installed to the specified or current project.
        /// </summary>
        /// <param name="projects"></param>
        /// <param name="identity"></param>
        private async Task SyncPackages(IEnumerable <NuGetProject> projects, PackageIdentity identity)
        {
            try
            {
                using (var sourceCacheContext = new SourceCacheContext())
                {
                    var resolutionContext = new ResolutionContext(
                        GetDependencyBehavior(),
                        _allowPrerelease,
                        false,
                        VersionConstraints.None,
                        new GatherCache(),
                        sourceCacheContext);

                    foreach (var project in projects)
                    {
                        await InstallPackageByIdentityAsync(project, identity, resolutionContext, this, WhatIf.IsPresent);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
            finally
            {
                BlockingCollection.Add(new ExecutionCompleteMessage());
            }
        }
예제 #13
0
        private void ResetSolutionSettings()
        {
            string root;

            if (SolutionManager == null ||
                !SolutionManager.IsSolutionOpen ||
                string.IsNullOrEmpty(SolutionManager.SolutionDirectory))
            {
                root = null;
            }
            else
            {
                root = Path.Combine(SolutionManager.SolutionDirectory, NuGetSolutionSettingsFolder);
            }

            try
            {
                _solutionSettings = Configuration.Settings.LoadDefaultSettings(root, configFileName: null, machineWideSettings: MachineWideSettings);
            }
            catch (Configuration.NuGetConfigurationException ex)
            {
                MessageHelper.ShowErrorMessage(ExceptionUtilities.DisplayMessage(ex), Strings.ConfigErrorDialogBoxTitle);
            }

            if (_solutionSettings == null)
            {
                _solutionSettings = Configuration.NullSettings.Instance;
            }
        }
예제 #14
0
        /// <summary>
        /// Update or reinstall a single package installed to a solution. For Update-Package -Id or Update-Package -Id
        /// -Reinstall.
        /// </summary>
        /// <returns></returns>
        private async Task UpdateOrReinstallSinglePackageAsync()
        {
            try
            {
                var isPackageInstalled = await IsPackageInstalledAsync(Id);

                if (isPackageInstalled)
                {
                    await PreviewAndExecuteUpdateActionsForSinglePackage();
                }
                else
                {
                    // set nuget operation status to NoOp when package is not even installed
                    _status = NuGetOperationStatus.NoOp;
                    Log(MessageLevel.Error, Resources.Cmdlet_PackageNotInstalledInAnyProject, Id);
                }
            }
            catch (Exception ex)
            {
                _status = NuGetOperationStatus.Failed;
                Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
            finally
            {
                BlockingCollection.Add(new ExecutionCompleteMessage());
            }
        }
예제 #15
0
        /// <summary>
        /// Update or reinstall all packages installed to a solution. For Update-Package or Update-Package -Reinstall.
        /// </summary>
        /// <returns></returns>
        private async Task UpdateOrReinstallAllPackagesAsync()
        {
            try
            {
                using (var sourceCacheContext = new SourceCacheContext())
                {
                    var resolutionContext = new ResolutionContext(
                        GetDependencyBehavior(),
                        _allowPrerelease,
                        false,
                        DetermineVersionConstraints(),
                        new GatherCache(),
                        sourceCacheContext);

                    // if the source is explicitly specified we will use exclusively that source otherwise use ALL enabled sources
                    var actions = await PackageManager.PreviewUpdatePackagesAsync(
                        Projects,
                        resolutionContext,
                        this,
                        PrimarySourceRepositories,
                        PrimarySourceRepositories,
                        Token);

                    if (!actions.Any())
                    {
                        _status = NuGetOperationStatus.NoOp;
                    }
                    else
                    {
                        _packageCount = actions.Select(action => action.PackageIdentity.Id).Distinct().Count();
                    }

                    await ExecuteActions(actions, sourceCacheContext);
                }
            }
            catch (SignatureException ex)
            {
                // set nuget operation status to failed when an exception is thrown
                _status = NuGetOperationStatus.Failed;

                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Log(LogUtility.LogLevelToMessageLevel(LogLevel.Error), ex.AsLogMessage().FormatWithCode());
                }

                var logMessages = ex.Results.SelectMany(p => p.Issues).ToList();

                logMessages.ForEach(p => Log(LogUtility.LogLevelToMessageLevel(p.Level), p.FormatWithCode()));
            }
            catch (Exception ex)
            {
                _status = NuGetOperationStatus.Failed;
                Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
            finally
            {
                BlockingCollection.Add(new ExecutionCompleteMessage());
            }
        }
        private async Task <SortedDictionary <NuGetVersion, PackageInfo> > FindPackagesByIdAsync(string id, CancellationToken cancellationToken)
        {
            for (var retry = 0; retry != 3; ++retry)
            {
                var baseUri = _baseUris[retry % _baseUris.Count].OriginalString;
                var uri     = baseUri + id.ToLowerInvariant() + "/index.json";

                try
                {
                    using (var result = await _httpSource.GetAsync(
                               new HttpSourceCachedRequest(
                                   uri,
                                   $"list_{id}",
                                   CreateCacheContext(retry))
                    {
                        IgnoreNotFounds = true,
                        EnsureValidContents = stream => HttpStreamValidation.ValidateJObject(uri, stream)
                    },
                               Logger,
                               cancellationToken))
                    {
                        if (result.Status == HttpSourceResultStatus.NotFound)
                        {
                            return(new SortedDictionary <NuGetVersion, PackageInfo>());
                        }

                        try
                        {
                            return(ConsumeFlatContainerIndex(result.Stream, id, baseUri));
                        }
                        catch
                        {
                            Logger.LogWarning(string.Format(CultureInfo.CurrentCulture, Strings.Log_FileIsCorrupt, result.CacheFileName));

                            throw;
                        }
                    }
                }
                catch (Exception ex) when(retry < 2)
                {
                    var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_RetryingFindPackagesById, nameof(FindPackagesByIdAsync), uri)
                                  + Environment.NewLine
                                  + ExceptionUtilities.DisplayMessage(ex);

                    Logger.LogMinimal(message);
                }
                catch (Exception ex) when(retry == 2)
                {
                    var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_FailedToRetrievePackage, uri);

                    Logger.LogError(message + Environment.NewLine + ExceptionUtilities.DisplayMessage(ex));

                    throw new FatalProtocolException(message, ex);
                }
            }

            return(null);
        }
        public override async Task <DownloadResourceResult> GetDownloadResourceResultAsync(
            PackageIdentity identity,
            ISettings settings,
            ILogger logger,
            CancellationToken token)
        {
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }

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

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

            token.ThrowIfCancellationRequested();

            var  sourcePackage = identity as SourcePackageDependencyInfo;
            bool isFromUri     = sourcePackage?.PackageHash != null &&
                                 sourcePackage?.DownloadUri != null;

            try
            {
                if (isFromUri)
                {
                    // If this is a SourcePackageDependencyInfo object with everything populated
                    // and it is from an online source, use the machine cache and download it using the
                    // given url.
                    return(await _feedParser.DownloadFromUrl(sourcePackage, sourcePackage.DownloadUri, settings, logger, token));
                }
                else
                {
                    // Look up the package from the id and version and download it.
                    return(await _feedParser.DownloadFromIdentity(identity, settings, logger, token));
                }
            }
            catch (OperationCanceledException)
            {
                return(new DownloadResourceResult(DownloadResourceResultStatus.Cancelled));
            }
            catch (Exception ex) when(!(ex is FatalProtocolException))
            {
                // if the expcetion is not FatalProtocolException, catch it.
                string message = string.Format(CultureInfo.CurrentCulture, Strings.Log_ErrorDownloading, identity, _feedParser.Source.Source);

                logger.LogError(message + Environment.NewLine + ExceptionUtilities.DisplayMessage(ex));

                throw new FatalProtocolException(message, ex);
            }
        }
예제 #18
0
        static string DisplayMessage(Exception ex)
        {
            string errorMessage = ExceptionUtilities.DisplayMessage(ex);

            // NSUrlSessionHandler exceptions contain curly braces {} in the UserInfo part of the message so
            // to avoid a FormatException we need to escape these.
            return(errorMessage
                   .Replace("{", "{{")
                   .Replace("}", "}}"));
        }
 /// <summary>
 /// Async call for install a package by Id.
 /// </summary>
 async Task InstallPackageByIdAsync()
 {
     try {
         await InstallPackageByIdAsync(DTEProject, Id, GetDependencyBehavior(), allowPrerelease, WhatIf.IsPresent);
     } catch (Exception ex) {
         Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
     } finally {
         BlockingCollection.Add(new ExecutionCompleteMessage());
     }
 }
예제 #20
0
 /// <summary>
 /// Async call for uninstall a package from the current project
 /// </summary>
 async Task UninstallPackageAsync()
 {
     try {
         await UninstallPackageByIdAsync(DTEProject, Id, UninstallContext, WhatIf.IsPresent);
     } catch (Exception ex) {
         Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
     } finally {
         BlockingCollection.Add(new ExecutionCompleteMessage());
     }
 }
 /// <summary>
 /// Update or reinstall a single package installed to a solution. For Update-Package -Id or Update-Package -Id
 /// -Reinstall.
 /// </summary>
 async Task UpdateOrReinstallSinglePackageAsync()
 {
     try {
         await PreviewAndExecuteUpdateActionsForSinglePackage();
     } catch (Exception ex) {
         Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
     } finally {
         BlockingCollection.Add(new ExecutionCompleteMessage());
     }
 }
예제 #22
0
 public void ExecuteCommand(string command)
 {
     try {
         EnsureHostInitialized();
         rpc.InvokeAsync(Methods.InvokeName, command).Wait();
     } catch (Exception ex) {
         string errorMessage = ExceptionUtilities.DisplayMessage(ex);
         scriptingConsole.WriteLine(errorMessage, ScriptingStyle.Error);
     }
 }
예제 #23
0
        private async Task <RepositorySignatureResource> GetRepositorySignatureResourceAsync(
            SourceRepository source,
            string repoSignUrl,
            ILogger log,
            CancellationToken token)
        {
            var httpSourceResource = await source.GetResourceAsync <HttpSourceResource>(token);

            var client = httpSourceResource.HttpSource;

            for (var retry = 0; retry < 3; retry++)
            {
                using (var sourecCacheContext = new SourceCacheContext())
                {
                    var cacheContext = HttpSourceCacheContext.Create(sourecCacheContext, retry);

                    try
                    {
                        return(await client.GetAsync(
                                   new HttpSourceCachedRequest(
                                       repoSignUrl,
                                       "repository_signature",
                                       cacheContext)
                        {
                            EnsureValidContents = stream => HttpStreamValidation.ValidateJObject(repoSignUrl, stream),
                            MaxTries = 1
                        },
                                   async httpSourceResult =>
                        {
                            var json = await httpSourceResult.Stream.AsJObjectAsync();

                            return new RepositorySignatureResource(json, source);
                        },
                                   log,
                                   token));
                    }
                    catch (Exception ex) when(retry < 2)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_RetryingRepositorySignature, repoSignUrl)
                                      + Environment.NewLine
                                      + ExceptionUtilities.DisplayMessage(ex);

                        log.LogMinimal(message);
                    }
                    catch (Exception ex) when(retry == 2)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_FailedToReadRepositorySignature, repoSignUrl);

                        throw new FatalProtocolException(message, ex);
                    }
                }
            }

            return(null);
        }
예제 #24
0
        private async Task UpdateAllPackages(string solutionDir, INuGetProjectContext projectContext)
        {
            Console.WriteLine(LocalizedResourceManager.GetString("ScanningForProjects"));

            // Search recursively for all packages.xxx.config files
            string[] packagesConfigFiles = Directory.GetFiles(
                solutionDir, "*.config", SearchOption.AllDirectories);

            var projects = packagesConfigFiles.Where(s => Path.GetFileName(s).StartsWith("packages.", StringComparison.OrdinalIgnoreCase))
                           .Select(s => GetProject(s, projectContext))
                           .Where(p => p != null)
                           .Distinct()
                           .ToList();

            if (projects.Count == 0)
            {
                Console.WriteLine(LocalizedResourceManager.GetString("NoProjectsFound"));
                return;
            }

            if (projects.Count == 1)
            {
                Console.WriteLine(LocalizedResourceManager.GetString("FoundProject"), projects.Single().ProjectName);
            }
            else
            {
                Console.WriteLine(LocalizedResourceManager.GetString("FoundProjects"), projects.Count, String.Join(", ", projects.Select(p => p.ProjectName)));
            }

            string repositoryPath = GetRepositoryPathFromSolution(solutionDir);

            foreach (var project in projects)
            {
                try
                {
                    await UpdatePackagesAsync(project, repositoryPath);

                    if (Verbose)
                    {
                        Console.WriteLine();
                    }
                }
                catch (Exception e)
                {
                    if (Console.Verbosity == Verbosity.Detailed || ExceptionLogger.Instance.ShowStack)
                    {
                        Console.WriteWarning(e.ToString());
                    }
                    else
                    {
                        Console.WriteWarning(ExceptionUtilities.DisplayMessage(e));
                    }
                }
            }
        }
예제 #25
0
        private async Task <ICredentials> PromptForCredentialsAsync(
            CredentialRequestType type,
            string message,
            AmbientAuthenticationState authState,
            ILogger log,
            CancellationToken token)
        {
            ICredentials promptCredentials;

            // Only one prompt may display at a time.
            await _credentialPromptLock.WaitAsync();

            try
            {
                // Get the proxy for this URI so we can pass it to the credentialService methods
                // this lets them use the proxy if they have to hit the network.
                var proxyCache = ProxyCache.Instance;
                var proxy      = proxyCache?.GetProxy(_packageSource.SourceUri);

                promptCredentials = await _credentialService
                                    .GetCredentialsAsync(_packageSource.SourceUri, proxy, type, message, token);

                if (promptCredentials == null)
                {
                    // If this is the case, this means none of the credential providers were able to
                    // handle the credential request or no credentials were available for the
                    // endpoint.
                    authState.Block();
                }
                else
                {
                    authState.Increment();
                }
            }
            catch (OperationCanceledException)
            {
                // This indicates a non-human cancellation.
                throw;
            }
            catch (Exception e)
            {
                // If this is the case, this means there was a fatal exception when interacting
                // with the credential service (or its underlying credential providers). Either way,
                // block asking for credentials for the live of this operation.
                log.LogError(ExceptionUtilities.DisplayMessage(e));
                promptCredentials = null;
                authState.Block();
            }
            finally
            {
                _credentialPromptLock.Release();
            }

            return(promptCredentials);
        }
        /// <summary>
        /// Async call for install a package by Id.
        /// </summary>
        /// <param name="identities"></param>
        private async Task InstallPackageByIdAsync()
        {
            try
            {
                using (var sourceCacheContext = new SourceCacheContext())
                {
                    var resolutionContext = new ResolutionContext(
                        GetDependencyBehavior(),
                        _allowPrerelease,
                        false,
                        VersionConstraints.None,
                        new GatherCache(),
                        sourceCacheContext);

                    await InstallPackageByIdAsync(Project, Id, resolutionContext, this, WhatIf.IsPresent);
                }
            }
            catch (FatalProtocolException ex)
            {
                _status = NuGetOperationStatus.Failed;

                // Additional information about the exception can be observed by using the -verbose switch with the install-package command
                Log(MessageLevel.Debug, ExceptionUtilities.DisplayMessage(ex));

                // Wrap FatalProtocolException coming from the server with a user friendly message
                var error = string.Format(CultureInfo.CurrentUICulture, Resources.Exception_PackageNotFound, Id, Source);
                Log(MessageLevel.Error, error);
            }
            catch (SignatureException ex)
            {
                // set nuget operation status to failed when an exception is thrown
                _status = NuGetOperationStatus.Failed;

                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Log(ex.AsLogMessage());
                }

                if (ex.Results != null)
                {
                    var logMessages = ex.Results.SelectMany(p => p.Issues).ToList();

                    logMessages.ForEach(p => Log(p));
                }
            }
            catch (Exception ex)
            {
                _status = NuGetOperationStatus.Failed;
                Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
            }
            finally
            {
                BlockingCollection.Add(new ExecutionCompleteMessage());
            }
        }
 private void LoadSettings()
 {
     try
     {
         _settings = ServiceLocator.GetInstance<ISettings>();
         Debug.Assert(_settings != null);
     }
     catch (Exception e)
     {
         MessageHelper.ShowErrorMessage(ExceptionUtilities.DisplayMessage(e), Resources.ErrorDialogBoxTitle);
     }
 }
 /// <summary>
 /// Async call for install packages from the list of identities.
 /// </summary>
 async Task InstallPackagesAsync(IEnumerable <PackageIdentity> identities)
 {
     try {
         foreach (var identity in identities)
         {
             await InstallPackageByIdentityAsync(DTEProject, identity, GetDependencyBehavior(), allowPrerelease, WhatIf.IsPresent);
         }
     } catch (Exception ex) {
         Log(MessageLevel.Error, ExceptionUtilities.DisplayMessage(ex));
     } finally {
         BlockingCollection.Add(new ExecutionCompleteMessage());
     }
 }
        public void ExecuteCommand(string command)
        {
            try {
                CreateRunspace();

                using (Pipeline pipeline = CreatePipeline(command)) {
                    pipeline.Invoke();
                }
            } catch (Exception ex) {
                string errorMessage = ExceptionUtilities.DisplayMessage(ex);
                scriptingConsole.WriteLine(errorMessage, ScriptingStyle.Error);
            }
        }
예제 #30
0
        public void ShowError(Exception ex)
        {
            var signException = ex as SignatureException;

            if (signException != null)
            {
                foreach (var result in signException.Results)
                {
                    ProcessSignatureIssues(result, signException.PackageIdentity);
                }
            }
            else
            {
                if (ex is NuGetResolverConstraintException ||
                    ex is PackageAlreadyInstalledException ||
                    ex is MinClientVersionException ||
                    ex is FrameworkException ||
                    ex is NuGetProtocolException ||
                    ex is PackagingException ||
                    ex is InvalidOperationException ||
                    ex is PackageReferenceRollbackException)
                {
                    // for exceptions that are known to be normal error cases, just
                    // display the message.
                    ProjectContext.Log(MessageLevel.Info, ExceptionUtilities.DisplayMessage(ex, indent: true));

                    // write to activity log
                    var activityLogMessage = string.Format(CultureInfo.CurrentCulture, ex.ToString());
                    ActivityLog.LogError(LogEntrySource, activityLogMessage);

                    // Log additional messages to the error list to provide context on why the rollback failed
                    var rollbackException = ex as PackageReferenceRollbackException;
                    if (rollbackException != null)
                    {
                        foreach (var message in rollbackException.LogMessages)
                        {
                            if (message.Level == LogLevel.Error)
                            {
                                UILogger.ReportError(message.Message);
                            }
                        }
                    }
                }
                else
                {
                    ProjectContext.Log(MessageLevel.Error, ex.ToString());
                }

                UILogger.ReportError(ExceptionUtilities.DisplayMessage(ex, indent: false));
            }
        }