Beispiel #1
0
        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 WebProjectManager(string remoteSource, string siteRoot)
 {
     string webRepositoryDirectory = GetWebRepositoryDirectory(siteRoot);
     Uri uri = new Uri(remoteSource);
     IPackageRepository repository = new DataServicePackageRepository(uri);//PackageRepositoryFactory.Default.CreateRepository(remoteSource);
     IPackagePathResolver resolver = new DefaultPackagePathResolver(webRepositoryDirectory);
     IPackageRepository repository2 = new LocalPackageRepository(webRepositoryDirectory, false); //PackageRepositoryFactory.Default.CreateRepository(webRepositoryDirectory);
     IProjectSystem system = new WebProjectSystem(siteRoot);
     ((DataServicePackageRepository)repository).ProgressAvailable += new EventHandler<ProgressEventArgs>(repository_ProgressAvailable);
     //((DataServicePackageRepository)repository).SendingRequest += new EventHandler<WebRequestEventArgs>(repository_sendingRequest);
     this._projectManager = new ProjectManager(repository, resolver, system, repository2);
     _projectManager.Logger = new LoggerController();
 }
Beispiel #3
0
        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);
                                 }
                             });
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Syntax: NugetDownloader targetFolder numOfPackages");
                return;
            }

            var downloadFolder = new DirectoryInfo(args[0]);
            var packageCount = Int32.Parse(args[1]);
            var localRepository = new LocalPackageRepository(downloadFolder.FullName);

            DataServicePackageRepository remoteRepo = null;
            try
            {
                remoteRepo = new DataServicePackageRepository(nugetUri);

                var packages = remoteRepo.GetPackages()
                    .Where(p => p.IsLatestVersion)
                    .OrderByDescending(p => p.DownloadCount)
                    .Take(packageCount);

                foreach (IPackage eachPackage in packages)
                {
                    try
                    {
                        Console.Write(eachPackage.Id + " " + eachPackage.Version + " ... ");
                        localRepository.AddPackage(eachPackage);
                        Console.WriteLine("OK");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("FAILED");
                        Console.WriteLine("[EXCEPTION] " + ex.Message);
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("[EXCEPTION] " + ex.Message);
                return;
            }

            foreach (var file in downloadFolder.EnumerateFiles("*.nupkg", SearchOption.AllDirectories))
            {
                try
                {
                    var targetPath = Path.Combine(downloadFolder.FullName, file.Name);
                    if (!File.Exists(targetPath))
                        file.MoveTo(targetPath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[EXCEPTION] " + ex.Message);
                }
            }

            foreach (var dir in downloadFolder.EnumerateDirectories())
            {
                dir.Delete(true);
            }
        }
Beispiel #5
0
        /// <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 DataServicePackageRepository GetPackageRepository()
 {
     if (_packageRepository == null || _packageRepository.Source != _redirectedlPackageSource) {
         try {
             Uri packageUri = new Uri(PackageSource);
             IWebProxy packageSourceProxy = _proxyService.GetProxy(packageUri);
             IHttpClient packageSourceClient = new RedirectedHttpClient(packageUri, packageSourceProxy);
             _packageRepository = new DataServicePackageRepository(packageSourceClient);
             _redirectedlPackageSource = _packageRepository.Source;
         }
         catch (Exception) {
             _packageRepository = null;
         }
     }
     return _packageRepository;
 }
Beispiel #7
0
        private static void Latest()
        {
            var orchard = new DataServicePackageRepository(new Uri("http://packages.orchardproject.net/FeedService.svc"));
            var nuget = new DataServicePackageRepository(new Uri("https://nuget.org/api/v2"));
            var symbolsource =
                new DataServicePackageRepository(new Uri("http://nuget.gw.symbolsource.org/Public/Orchard/FeedService.mvc"));
            var cache = Directory.GetCurrentDirectory();

            var solution = new ProjectCollection();
            var logger = new ConsoleLogger();

            foreach (var d in Directory.EnumerateDirectories(Path.Combine(cache, "aa", "Content", "Modules")))
            {
                var project = solution.LoadProject(Path.Combine(d, Path.GetFileName(d) + ".csproj"));
                project.RemoveItem(
                    project.Items.Where(i => i.ItemType == "ProjectReference" && i.GetMetadataValue("Name") == "Orchard.Core").
                        Single());
                project.RemoveItem(
                    project.Items.Where(
                        i => i.ItemType == "ProjectReference" && i.GetMetadataValue("Name") == "Orchard.Framework").Single());
                project.AddItem("Reference", "Orchard.Core",
                                new[]
                                    {
                                        new KeyValuePair<string, string>("HintPath",
                                                                         @"C:\Users\marcin.mikolajczak\Downloads\Temp\Orchard.Core.dll")
                                    });
                project.AddItem("Reference", "Orchard.Framework",
                                new[]
                                    {
                                        new KeyValuePair<string, string>("HintPath",
                                                                         @"C:\Users\marcin.mikolajczak\Downloads\Temp\Orchard.Framework.dll")
                                    });
            }

            foreach (var project in solution.LoadedProjects)
                project.Build(logger);
        }