public static int Main(string[] args) { try { Console.WriteLine("NuGet bootstrapper {0}", typeof(Program).Assembly.GetName().Version); // Setup the proxy for gallery requests Uri galleryUri = new Uri(GalleryUrl); // Register a console based credentials provider so that the user get's prompted if a password // is required for the proxy HttpClient.DefaultCredentialProvider = new ConsoleCredentialProvider(); // Setup IHttpClient for the Gallery to locate packages var httpClient = new HttpClient(galleryUri); // Get the package from the feed var repository = new DataServicePackageRepository(httpClient); var packageMetadata = repository.GetPackages().Where(p => p.Id.ToLower() == NuGetCommandLinePackageId) .AsEnumerable() .OrderByDescending(p => Version.Parse(p.Version)) .FirstOrDefault(); if (packageMetadata != null) { Console.WriteLine("Found NuGet.exe version {0}.", packageMetadata.Version); Console.WriteLine("Downloading..."); Uri uri = repository.GetReadStreamUri(packageMetadata); var downloadClient = new HttpClient(uri); var packageStream = new MemoryStream(downloadClient.DownloadData()); using (Package package = Package.Open(packageStream)) { var fileUri = PackUriHelper.CreatePartUri(new Uri(NuGetExeFilePath, UriKind.Relative)); PackagePart nugetExePart = package.GetPart(fileUri); if (nugetExePart != null) { // Get the exe path and move it to a temp file (NuGet.exe.old) so we can replace the running exe with the bits we got // from the package repository string exePath = typeof(Program).Assembly.Location; string renamedPath = exePath + ".old"; Move(exePath, renamedPath); // Update the file UpdateFile(exePath, nugetExePart); Console.WriteLine("Update complete."); } } } return 0; } catch (Exception e) { WriteError(e); } return 1; }
public virtual void DownloadPackage(Uri uri, IPackageMetadata package, Stream targetStream) { if (uri == null) { throw new ArgumentNullException("uri"); } var downloadClient = new HttpClient(uri) { UserAgent = HttpUtility.CreateUserAgentString(DefaultUserAgentClient) }; DownloadPackage(downloadClient, package, targetStream); }
public HttpClient get_client(string baseUrl, string path, string method, string contentType) { this.Log().Debug(() => "Getting httpclient for '{0}' with '{1}'".format_with(baseUrl, path)); Uri requestUri = get_service_endpoint_url(baseUrl, path); var client = new HttpClient(requestUri) { ContentType = contentType, Method = method, UserAgent = "{0}/{1}".format_with(ApplicationParameters.Name, ApplicationParameters.FileVersion) }; return client; }
private Uri GetResponseUri(HttpClient client) { using (WebResponse response = client.GetResponse()) { if (response == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToResolveUri, Uri)); } return response.ResponseUri; } }
public virtual IPackage DownloadPackage(Uri uri, IPackageMetadata package) { if (uri == null) { throw new ArgumentNullException("uri"); } if (package == null) { throw new ArgumentNullException("package"); } var downloadClient = new HttpClient(uri) { UserAgent = HttpUtility.CreateUserAgentString(DefaultUserAgentClient) }; return DownloadPackage(downloadClient, package); }
private HttpClient GetClient(string path, string method, string contentType) { var baseUrl = _baseUri.Value; Uri requestUri = GetServiceEndpointUrl(baseUrl, path); var client = new HttpClient(requestUri) { ContentType = contentType, Method = method }; if (!String.IsNullOrEmpty(_userAgent)) { client.UserAgent = HttpUtility.CreateUserAgentString(_userAgent); } return client; }
public IPackage DownloadPackage(Uri uri, byte[] packageHash, IPackageMetadata package) { if (uri == null) { throw new ArgumentNullException("uri"); } if (packageHash == null) { throw new ArgumentNullException("packageHash"); } if (package == null) { throw new ArgumentNullException("package"); } var downloadClient = new HttpClient(uri); downloadClient.UserAgent = HttpUtility.CreateUserAgentString(DefaultUserAgentClient); return DownloadPackage(downloadClient, packageHash, package); }
public static int Main(string[] args) { string _exePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"NuGet\NuGet.exe"); try { var processInfo = new ProcessStartInfo(_exePath) { UseShellExecute = false, WorkingDirectory = Environment.CurrentDirectory }; if (!File.Exists(_exePath)) { // Register a console based credentials provider so that the user get's prompted if a password // is required for the proxy HttpClient.DefaultCredentialProvider = new ConsoleCredentialProvider(); // Setup IHttpClient for the Gallery to locate packages var httpClient = new HttpClient(new Uri("http://nuget.org/NuGet.exe")); httpClient.UserAgent = "Bootstrapper/" + typeof(Program).Assembly.GetName().Version; File.WriteAllBytes(_exePath, httpClient.DownloadData()); } else if ((DateTime.UtcNow - File.GetLastWriteTime(_exePath)).TotalDays > 10) { // Check for updates to the exe every 10 days processInfo.Arguments = "update -self"; RunProcess(processInfo); File.SetLastAccessTimeUtc(_exePath, DateTime.UtcNow); } processInfo.Arguments = ParseArgs(); RunProcess(processInfo); return 0; } catch (Exception e) { WriteError(e); } return 1; }
private void InitializeRedirectedClient() { // Cache an internal HttpClient object so that // we don't have to go through the forwarding link // every single time thus slowing down the connection to the // original source. if (null == _cachedRedirectClient) { IHttpClient originalClient = new HttpClient(_originalUri, Proxy); WebRequest request = originalClient.CreateRequest(); using (WebResponse response = request.GetResponse()) { if (null == response) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, "Unable to get a valid response for link: {0}", Uri.OriginalString)); } _cachedRedirectClient = new HttpClient(response.ResponseUri); } } }
public void RunFromGallery() { Directory.CreateDirectory(_targetDirectory); var client = new HttpClient(DeveloperFeed); client.SendingRequest += (sender, e) => { e.Request.Credentials = _credentials; e.Request.PreAuthenticate = true; }; var remoteRepo = new DataServicePackageRepository(client); var targetRepo = new LocalPackageRepository(_targetDirectory); var packages = remoteRepo.GetPackages() .Where(p => p.IsAbsoluteLatestVersion) .ToList(); Parallel.ForEach(packages, new ParallelOptions { MaxDegreeOfParallelism = 4 }, package => { // Some packages are updated without revving the version. We'll only opt not to re-download // a package if an identical version does not exist on disk. var existingPackage = targetRepo.FindPackage(package.Id, package.Version); var dataServicePackage = (DataServicePackage)package; if (existingPackage == null || !existingPackage.GetHash(dataServicePackage.PackageHashAlgorithm).Equals(dataServicePackage.PackageHash, StringComparison.Ordinal)) { Trace.WriteLine(string.Format("{0}: Adding package {1}", DateTime.Now, package.GetFullName())); var packagePath = GetPackagePath(package); using (var input = package.GetStream()) using (var output = File.Create(packagePath)) { input.CopyTo(output); } PurgeOldVersions(targetRepo, package); } }); }
private static WebRequest CreateRequest(Uri uri) { IHttpClient client = new HttpClient(uri); WebRequest request = client.CreateRequest(); return request; }
private static void EnsureSuccessfulResponse(HttpClient client) { WebResponse response = null; try { response = client.GetResponse(); } catch (WebException e) { if (e.Response == null) { throw; } response = e.Response; var httpResponse = (HttpWebResponse)e.Response; if (httpResponse != null && !AcceptableStatusCodes.Contains(httpResponse.StatusCode)) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, httpResponse.StatusDescription, e.Message), e); } } finally { if (response != null) { response.Close(); response = null; } } }
static Stream GetResponseStream (Uri uri) { if (uri.IsFile) { var request = WebRequest.Create (uri); return request.GetResponse ().GetResponseStream (); } var httpClient = new HttpClient (uri); return httpClient.GetResponse ().GetResponseStream (); }
/// <summary> /// Ensures that success response is received. /// </summary> /// <param name="client">The client that is making the request.</param> /// <param name="expectedStatusCode">The exected status code.</param> /// <returns>True if success response is received; false if redirection response is received. /// In this case, _baseUri will be updated to be the new redirected Uri and the requrest /// should be retried.</returns> private bool EnsureSuccessfulResponse(HttpClient client, HttpStatusCode? expectedStatusCode = null) { HttpWebResponse response = null; try { response = (HttpWebResponse)client.GetResponse(); if (response != null && ((expectedStatusCode.HasValue && expectedStatusCode.Value != response.StatusCode) || // If expected status code isn't provided, just look for anything 400 (Client Errors) or higher (incl. 500-series, Server Errors) // 100-series is protocol changes, 200-series is success, 300-series is redirect. (!expectedStatusCode.HasValue && (int)response.StatusCode >= 400))) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, String.Empty)); } return true; } catch (WebException e) { if (e.Response == null) { throw; } response = (HttpWebResponse)e.Response; // Check if the error is caused by redirection if (response.StatusCode == HttpStatusCode.MultipleChoices || response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.SeeOther || response.StatusCode == HttpStatusCode.TemporaryRedirect) { var location = response.Headers["Location"]; Uri newUri; if (!Uri.TryCreate(client.Uri, location, out newUri)) { throw; } _baseUri = new Lazy<Uri>(() => newUri); return false; } if (expectedStatusCode != response.StatusCode) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, e.Message), e); } return true; } finally { if (response != null) { response.Close(); response = null; } } }
/// <summary> /// Do not use cached credentials for the first request sent to a package source. /// /// Once NuGet has a valid credential for a package source it is used from that point /// onwards. So if the user changes a valid username/password in Preferences /// to a non-valid username/password they will not see the 'Invalid credentials' /// warning. To workaround this caching we remove the credentials for the request /// the first time it is sent. Also the UseDefaultCredentials is set to true. /// This forces NuGet to get the credentials from the IPackageSourceProvider, /// which is implemented by the RegisteredPackageSourcesViewModel, and will /// contain the latest usernames and passwords for all package sources. /// </summary> HttpClient CreateHttpClient(PackageSourceViewModel packageSource) { var httpClient = new HttpClient (new Uri (packageSource.SourceUrl)); bool resetCredentials = true; httpClient.SendingRequest += (sender, e) => { if (resetCredentials && packageSource.HasPassword ()) { resetCredentials = false; e.Request.Credentials = null; e.Request.UseDefaultCredentials = true; } }; return httpClient; }
/// <summary> /// Ensures that success response is received. /// </summary> /// <param name="client">The client that is making the request.</param> /// <param name="expectedStatusCode">The exected status code.</param> /// <returns> /// True if success response is received; false if redirection response is received. /// In this case, _baseUri will be updated to be the new redirected Uri and the requrest /// should be retried. /// </returns> public NuGetServiceGetClientResult ensure_successful_response(HttpClient client, HttpStatusCode? expectedStatusCode = null) { this.Log().Debug(() => "Reaching out to '{0}'".format_with(client.Uri.to_string())); var result = new NuGetServiceGetClientResult { Success = false }; HttpWebResponse response = null; try { response = (HttpWebResponse)client.GetResponse(); result.Messages.Add( new ResultMessage { MessageType = ResultType.Note, Message = response != null ? response.StatusDescription : "Response was null" }); if (response != null && ((expectedStatusCode.HasValue && expectedStatusCode.Value != response.StatusCode) || // If expected status code isn't provided, just look for anything 400 (Client Errors) or higher (incl. 500-series, Server Errors) // 100-series is protocol changes, 200-series is success, 300-series is redirect. (!expectedStatusCode.HasValue && (int)response.StatusCode >= 400))) Bootstrap.handle_exception(new InvalidOperationException("Failed to process request.{0} '{1}'".format_with(Environment.NewLine, response.StatusDescription))); else result.Success = true; return result; } catch (WebException e) { if (e.Response == null) { Bootstrap.handle_exception(e); return result; } response = (HttpWebResponse)e.Response; // Check if the error is caused by redirection if (response.StatusCode == HttpStatusCode.MultipleChoices || response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.SeeOther || response.StatusCode == HttpStatusCode.TemporaryRedirect) { var location = response.Headers["Location"]; Uri newUri; if (!Uri.TryCreate(client.Uri, location, out newUri)) { Bootstrap.handle_exception(e); return result; } result.RedirectUrl = newUri.ToString(); return result; } result.Messages.Add( new ResultMessage { MessageType = ResultType.Note, Message = response.StatusDescription }); if (expectedStatusCode != response.StatusCode) Bootstrap.handle_exception(new InvalidOperationException("Failed to process request.{0} '{1}':{0} {2}".format_with(Environment.NewLine, response.StatusDescription, e.Message), e)); else result.Success = true; return result; } finally { if (response != null) { response.Close(); response = null; } } }
ImageLoadedEventArgs LoadImage (Uri uri, object state) { try { var httpClient = new HttpClient (uri); Stream stream = httpClient.GetResponse ().GetResponseStream (); Image image = Image.FromStream (stream); return new ImageLoadedEventArgs (image, uri, state); } catch (Exception ex) { return new ImageLoadedEventArgs (ex, uri, state); } }
protected internal virtual IHttpClient EnsureClient() { var originalClient = new HttpClient(_originalUri); return new HttpClient(GetResponseUri(originalClient)); }
/// <summary> /// </summary> private int Run(Assembly integrationAgentAssembly, string integrationAgentExeFileName, string integrationAgentExeDirectory, string[] args) { var parameters = Program.ParseArguments(args); var fileVersion = FileVersionInfo.GetVersionInfo(integrationAgentAssembly.Location).FileVersion; if (parameters.ShowVersion || parameters.ShowHelp) { Console.WriteLine("IntegrationAgent v" + fileVersion); } if (parameters.ShowHelp) { Program.ShowHelp(); } if (parameters.ShowVersion || parameters.ShowHelp) { return 0; } // Verify that assembly is signed and uses the correct key var traceWriter = Program.CreateTraceWriter(parameters.TraceLevel); traceWriter(TraceLevel.Verbose, "Checking assembly strong name."); if (!integrationAgentAssembly.HasValidStrongName()) { traceWriter(TraceLevel.Error, "Unsigned assembly!"); return 1; } traceWriter(TraceLevel.Verbose, "Verifying assembly signature."); if (!integrationAgentAssembly.PublicKeyTokenEqualsTo(Token.Bytes)) { traceWriter(TraceLevel.Error, "Invalid assembly!"); return 2; } // If no JSON config file name provided as paramter uses the application name traceWriter(TraceLevel.Verbose, "Looking for JSON config file."); var configFile = Path.Combine(integrationAgentExeDirectory, Path.GetFileNameWithoutExtension(integrationAgentExeFileName) + ".json"); if (!string.IsNullOrEmpty(parameters.Config)) { if (!parameters.Config.EndsWith(".json")) { parameters.Config = parameters.Config + ".json"; } configFile = Path.Combine(integrationAgentExeDirectory, parameters.Config); } // Check and reads the configuration file var configuration = new Configuration(); if (File.Exists(configFile)) { traceWriter(TraceLevel.Verbose, "Reading the JSON config file."); var configJson = File.ReadAllText(configFile); var jsonSerializer = new JavaScriptSerializer(); configuration = jsonSerializer.Deserialize<Configuration>(configJson) ?? configuration; traceWriter(TraceLevel.Verbose, "JSON config file loaded."); } // Merges config file and command line parameters. Command line paramters have precedence. configuration.package = parameters.Package ?? configuration.package; configuration.token = parameters.Token ?? configuration.token; configuration.repository = parameters.Repository ?? configuration.repository; configuration.repositoryUsername = parameters.RepositoryUsername ?? configuration.repositoryUsername; configuration.repositoryPassword = parameters.RepositoryPassword ?? configuration.repositoryPassword; traceWriter(TraceLevel.Verbose, "Checking input parameters."); if (string.IsNullOrWhiteSpace(configuration.package) && string.IsNullOrEmpty(configuration.token)) { traceWriter(TraceLevel.Error, "Invalid configuration!"); return 3; } // Initializes NuGet repositories traceWriter(TraceLevel.Verbose, "Initializing NuGet repositories."); var nugetRepository = new DataServicePackageRepository(new Uri(NuGetRepository)); var aggregateRepository = new AggregateRepository(new[] { nugetRepository }); if (Uri.IsWellFormedUriString(configuration.repository, UriKind.Absolute)) { if (!string.IsNullOrWhiteSpace(configuration.repositoryUsername) && !string.IsNullOrWhiteSpace(configuration.repositoryPassword)) { HttpClient.DefaultCredentialProvider = new NugetCredentialProvider( configuration.repositoryUsername, configuration.repositoryPassword); } var client = new HttpClient(new Uri(configuration.repository)); var customRepository = new DataServicePackageRepository(client); aggregateRepository = new AggregateRepository(new[] { customRepository, nugetRepository }); } // Perform auto-update if not disabled if (!parameters.DisableUpdates) { traceWriter(TraceLevel.Verbose, "Checking for self update."); var integrationAgentAssemblyName = integrationAgentAssembly.GetName(); var version = new SemanticVersion(integrationAgentAssemblyName.Version); var package = aggregateRepository .GetUpdates(new[] { new PackageName(integrationAgentAssemblyName.Name, version) }, includePrerelease: false, includeAllVersions: false) .OrderBy(p => p.Version) .LastOrDefault(); if (package != null && package.Version > version) { traceWriter(TraceLevel.Verbose, "Newer version found. Updating files."); var filename = Path.GetFileName(integrationAgentExeFileName); var file = package.GetFiles().FirstOrDefault(f => !string.IsNullOrEmpty(f.Path) && Path.GetFileName(f.Path).Equals(filename, StringComparison.OrdinalIgnoreCase)); if (file != null) { File.Delete(integrationAgentExeFileName + ".bak"); File.Move(integrationAgentExeFileName, integrationAgentExeFileName + ".bak"); using (Stream fromStream = file.GetStream(), toStream = File.Create(integrationAgentExeFileName)) { fromStream.CopyTo(toStream); } Process.Start(integrationAgentExeFileName, string.Join(" ", args) + " -disableupdates"); Environment.Exit(0); } } else { traceWriter(TraceLevel.Verbose, "Version is up to date."); } } // Install the package to run including its dependencies traceWriter(TraceLevel.Verbose, "Checking for execution package."); var packagesPath = Path.Combine(integrationAgentExeDirectory, "packages"); var remotePackage = aggregateRepository.FindPackagesById(configuration.package).OrderBy(p => p.Version).LastOrDefault(); var localRepository = new SharedPackageRepository(packagesPath); if (!localRepository.Exists(remotePackage)) { traceWriter(TraceLevel.Verbose, "Execution package not found localy. Installing remote."); var packageManager = new PackageManager(aggregateRepository, packagesPath); packageManager.InstallPackage(remotePackage, ignoreDependencies: false, allowPrereleaseVersions: false); } var localPackage = localRepository.FindPackagesById(configuration.package).OrderBy(p => p.Version).LastOrDefault(); if (localPackage == null) { traceWriter(TraceLevel.Error, "Package not found!"); return 4; } // Build a dictionary list of assemblies based on assembly fully qualified name for dynamically resolving from the loaded package traceWriter(TraceLevel.Verbose, "Resolving execution package dependencies."); var allAssemblies = localRepository .GetPackages() .ToArray() .SelectMany(p => p.AssemblyReferences.Select(a => { var path = Path.Combine(packagesPath, p.Id + "." + p.Version, a.Path); var aname = AssemblyName.GetAssemblyName(path); return new { key = aname.FullName, value = path }; })) .DistinctBy(i => i.key) .ToDictionary(i => i.key, i => i.value); AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => { var aname = new AssemblyName(eventArgs.Name); if (allAssemblies.ContainsKey(aname.FullName)) { return Assembly.LoadFile(allAssemblies[aname.FullName]); } return null; }; // Run the package export delegate if found var assemblies = localPackage.AssemblyReferences.Select(a => new AssemblyCatalog(Path.Combine(packagesPath, localPackage.Id + "." + localPackage.Version, a.Path))); using (var catalog = new AggregateCatalog(assemblies)) using (var container = new CompositionContainer(catalog)) { traceWriter(TraceLevel.Verbose, "Resolving execution package entry point."); container.SatisfyImportsOnce(this); if (this.RunAssembly == null) { traceWriter(TraceLevel.Error, "Execution package extry point not found!"); return 5; } traceWriter(TraceLevel.Verbose, "Invoking execution package extry point."); this.RunAssembly(configuration.token, traceWriter); traceWriter(TraceLevel.Verbose, "Execution package finished successfully."); return 0; } }
private static void EnsureSuccessfulResponse(HttpClient client, HttpStatusCode? expectedStatusCode = null) { HttpWebResponse response = null; try { response = (HttpWebResponse)client.GetResponse(); if (response != null && ((expectedStatusCode.HasValue && expectedStatusCode.Value != response.StatusCode) || // If expected status code isn't provided, just look for anything 400 (Client Errors) or higher (incl. 500-series, Server Errors) // 100-series is protocol changes, 200-series is success, 300-series is redirect. (!expectedStatusCode.HasValue && (int)response.StatusCode >= 400))) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, String.Empty)); } } catch (WebException e) { if (e.Response == null) { throw; } response = (HttpWebResponse)e.Response; if (expectedStatusCode != response.StatusCode) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, e.Message), e); } } finally { if (response != null) { response.Close(); response = null; } } }
private IHttpClient EnsureClient() { var originalClient = new HttpClient(_originalUri); return new HttpClient(GetResponseUri(originalClient)); }
static Stream GetResponseStream (Uri uri) { WebResponse response = null; if (uri.IsFile) { var request = WebRequest.Create (uri); response = request.GetResponse (); } else { var httpClient = new HttpClient (uri); response = httpClient.GetResponse (); } var stream = new MemoryStream (); response.GetResponseStream ().CopyTo (stream); // force the download to complete stream.Position = 0; return stream; }
private static void EnsureSuccessfulResponse(HttpClient client, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) { HttpWebResponse response = null; try { response = (HttpWebResponse)client.GetResponse(); if (response != null && expectedStatusCode != response.StatusCode) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, String.Empty)); } } catch (WebException e) { if (e.Response == null) { throw; } response = (HttpWebResponse)e.Response; if (expectedStatusCode != response.StatusCode) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, e.Message), e); } } finally { if (response != null) { response.Close(); response = null; } } }