private void DiscoverPackageSources()
        {
            if (String.IsNullOrEmpty(Url))
            {
                throw new CommandLineException(PsdResources.DiscoverCommandUrlRequired);
            }

            // do a best effort to add the protocol
            if (!Url.ToUpperInvariant().StartsWith("HTTP"))
            {
                Url = string.Format("http://{0}", Url);
            }

            Uri uri;
            if (!Uri.TryCreate(Url, UriKind.Absolute, out uri))
            {
                throw new CommandLineException(PsdResources.DiscoverCommandValidUrlRequired);
            }

            ValidateCredentials();

            var discovery = new PackageSourceDiscovery();
            discovery.SendingRequest += (sender, args) =>
            {
                if (!string.IsNullOrEmpty(UserName))
                {
                    var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(UserName + ":" + Password));
                    args.Request.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
                }

                if (!string.IsNullOrEmpty(ApiKey))
                {
                    args.Request.Headers.Add(ApiKeyHeader, ApiKey);
                }
            };

            var discoveryDocuments = discovery.FetchDiscoveryDocuments(uri);

            var sourceList = SourceProvider.LoadPackageSources().ToList();
            int counter = 0;
            foreach (var discoveryDocument in discoveryDocuments)
            {
                // REVIEW: Is this correct behaviour? Shouldn't we always overwrite?
                // Check if a package source already exists. Do not overwrite existing package sources.
                if (!sourceList.Any(ps => String.Equals(discoveryDocument.Title, ps.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    var source = discoveryDocument.AsPackageSource();
                    sourceList.Add(source);

                    var pushEndpoint = discoveryDocument.Endpoints.OrderByDescending(e => e.Preferred).FirstOrDefault(e => e.Name == FeedDiscoveryConstants.Discovery.PushV1 || e.Name == FeedDiscoveryConstants.Discovery.PushV2);
                    if (pushEndpoint != null && pushEndpoint.Settings.ContainsKey("apiKey"))
                    {
                        Settings.SetEncryptedValue(CommandLineUtility.ApiKeysSectionName, source.Source, pushEndpoint.Settings["apiKey"]);
                    }
                    counter++;
                }
            }

            SourceProvider.SavePackageSources(sourceList);
            Console.WriteLine(PsdResources.DiscoverCommandSuccessful, counter);
        }
        public void DiscoverPackageSourcesThrowsIfUrlIsNull(Uri uri)
        {
            // Arrange
            var discovery = new PackageSourceDiscovery();

            // Act and Assert
            ExceptionAssert.Throws<ArgumentNullException>(() => discovery.FetchDiscoveryDocuments(uri));
        }