Exemplo n.º 1
0
        private IEnumerable<ITaskItem> ResolvePackage(ITaskItem package)
        {
            string id = package.ItemSpec;
            string version = package.GetMetadata("Version");

            Log.LogMessage(MessageImportance.Normal, "Resolving Package Reference {0} {1}...", id, version);

            // Initial version just searches a machine-level repository

            var localFs = new PhysicalFileSystem(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Lib"));
            var defaultResolver = new DefaultPackagePathResolver(localFs);
            var machineRepo = new LocalPackageRepository(defaultResolver, localFs);
            var buildRepo = new BuildPackageRepository();
            var remoteRepo = new DataServicePackageRepository(new Uri("https://nuget.org/api/v2"));
            var project = new BuildProjectSystem(ProjectDirectory, new FrameworkName(TargetFramework), CurrentReferences);
            var manager = new PackageManager(remoteRepo, defaultResolver, localFs, machineRepo);
            var projectManager = new ProjectManager(remoteRepo, defaultResolver, project, buildRepo);

            // Install the package
            var ver = new SemanticVersion(version);
            manager.PackageInstalling += manager_PackageInstalling;
            manager.InstallPackage(id, ver);
            projectManager.AddPackageReference(id, ver);

            return project.OutputReferences.Select(item =>
            {
                var name = AssemblyName.GetAssemblyName(item);
                return new TaskItem(name.FullName, new Dictionary<string, string>() {
                    {"HintPath", item },
                    {"Private", "true"}
                });
            });
        }
Exemplo n.º 2
0
        public override async Task <Stream> GetStream(PackageIdentity identity, CancellationToken token)
        {
            Stream   result  = null;
            IPackage package = null;

            SemanticVersion version = SemanticVersion.Parse(identity.Version.ToString());

            // attempt a normal lookup first
            if (!V2Client.TryFindPackage(identity.Id, version, out package))
            {
                // skip further look ups for online repos
                DataServicePackageRepository v2Online = V2Client as DataServicePackageRepository;

                if (v2Online == null)
                {
                    IVersionComparer versionComparer = VersionComparer.VersionRelease;

                    // otherwise search further to find the package - this is needed for v2 non-normalized versions
                    V2Client.FindPackagesById(identity.Id).Any(p => versionComparer.Equals(identity.Version, NuGetVersion.Parse(p.ToString())));
                }
            }

            if (package != null)
            {
                result = package.GetStream();
            }

            return(result);
        }
Exemplo n.º 3
0
        public async Task Test()
        {
            await luceneRepository.AddPackageAsync(LoadSamplePackage("Package", "1.0.0"), CancellationToken.None);

            var repo = new DataServicePackageRepository(new Uri(ServerUrl + "api/odata/"));
            var results = repo.Search("", new string[0], allowPrereleaseVersions: false).ToList();
            Assert.That(results.Count, Is.EqualTo(1));
        }
Exemplo n.º 4
0
        public void ShowsVersionsFromMirror()
        {
            var repo = new DataServicePackageRepository(new Uri(ServerUrl + "api/odata/"));

            var result = repo.FindPackagesById("Nuget.Core");

            Assert.That(result.Count(), Is.GreaterThan(1), "Should look in mirror for packages.");
        }
Exemplo n.º 5
0
        public async Task Test()
        {
            await luceneRepository.AddPackageAsync(LoadSamplePackage("Package", "1.0.0"), CancellationToken.None);

            var repo    = new DataServicePackageRepository(new Uri(ServerUrl + "api/odata/"));
            var results = repo.Search("", new string[0], allowPrereleaseVersions: false).ToList();

            Assert.That(results.Count, Is.EqualTo(1));
        }
Exemplo n.º 6
0
        public void FindPackageMirrors()
        {
            var repo = new DataServicePackageRepository(new Uri(ServerUrl + "api/odata/"));

            var result = repo.FindPackage("Nuget.Core", new SemanticVersion("2.8.1"));

            Assert.That(result, Is.Not.Null, "Should mirror package from origin.");
            Assert.That(luceneRepository.LucenePackages.Count(), Is.EqualTo(1));
        }
Exemplo n.º 7
0
        static void Main(string [] args)
        {
            var options = new CliOptions();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // consume Options instance properties
                if (options.Verbose)
                {
                    Console.WriteLine(options.Repository);
                    Console.WriteLine(options.LocalDir);
                    Console.WriteLine(options.MaxConcurrentDownloads);
                }
                else
                {
                    Console.WriteLine("working ...");
                }
            }
            else
            {
                // Display the default usage information
                Console.WriteLine(options.GetUsage());
                return;
            }

            //Connect to the official package repository
            var repo = new DataServicePackageRepository(new Uri(options.Repository));

            //Get the list of all NuGet packages

            var skip = 0;

            var packages = new BlockingCollection <DataServicePackage>(5);

            var packageDownloaders = new Task[options.MaxConcurrentDownloads];

            for (int i = 0; i < options.MaxConcurrentDownloads; i++)
            {
                packageDownloaders[i] = Task.Run(() => RunPackageDownloader(packages, options.LocalDir));
            }

            // reading list of packages and add it to collection
            for (;;)
            {
                var packagesList = repo.GetPackages().Skip(skip).Take(10).ToList();
                if (packagesList.Count() == 0)
                {
                    packages.CompleteAdding();
                    break;
                }
                foreach (DataServicePackage p in packagesList)
                {
                    packages.Add(p);
                }
                skip += 10;
            }
        }
        public void Setup()
        {
            var mfs = new Mock<MockFileSystem>() { CallBase = true };
            var pr = new DefaultPackagePathResolver(mfs.Object);
            var mc = MachineCache.Default;
            var l = new LocalPackageRepository(pr, mfs.Object);

            var r1 = new DataServicePackageRepository(new Uri(@"http://nuget.org"));
            var r2 = new DataServicePackageRepository(new Uri(@"http://beta.nuget.org"));

            ar = new AggregateRepository(new List<IPackageRepository>() { mc, l, r1, r2 });
        }
        private IPackageRepository GetRepository()
        {
            var repository = V2Client as DataServicePackageRepository;

            if (repository != null)
            {
                var sourceUri = UriUtility.CreateSourceUri(repository.Source);
                repository = new DataServicePackageRepository(sourceUri);
            }

            // If the repository is not a DataServicePackageRepository just return the current one.
            return(repository ?? V2Client);
        }
Exemplo n.º 10
0
        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();
        }
        private DownloadResourceResult DownloadFromUrl(
            SourcePackageDependencyInfo package,
            DataServicePackageRepository repository,
            NuGet.Common.ILogger logger,
            CancellationToken token)
        {
            IPackage newPackage      = null;
            var      version         = SemanticVersion.Parse(package.Version.ToString());
            var      cacheRepository = MachineCache.Default;

            try
            {
                // Try finding the package in the machine cache
                var localPackage = cacheRepository.FindPackage(package.Id, version)
                                   as OptimizedZipPackage;

                // Validate the package matches the hash
                if (localPackage != null &&
                    localPackage.IsValid &&
                    MatchPackageHash(localPackage, package.PackageHash))
                {
                    newPackage = localPackage;
                }
            }
            catch
            {
                // Ignore cache failures here to match NuGet.Core
                // The bad package will be deleted and replaced during the download.
            }

            // If the local package does not exist in the cache download it from the source
            if (newPackage == null)
            {
                newPackage = DownloadToMachineCache(
                    cacheRepository,
                    package,
                    repository,
                    package.DownloadUri,
                    logger,
                    token);
            }

            // Read the package from the machine cache
            if (newPackage != null)
            {
                return(new DownloadResourceResult(newPackage.GetStream()));
            }

            return(null);
        }
Exemplo n.º 12
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);
 }
Exemplo n.º 13
0
        public void Setup()
        {
            var mfs = new Mock <MockFileSystem>()
            {
                CallBase = true
            };
            var pr = new DefaultPackagePathResolver(mfs.Object);
            var mc = MachineCache.Default;
            var l  = new LocalPackageRepository(pr, mfs.Object);

            var r1 = new DataServicePackageRepository(new Uri(@"http://nuget.org"));
            var r2 = new DataServicePackageRepository(new Uri(@"http://beta.nuget.org"));

            ar = new AggregateRepository(new List <IPackageRepository>()
            {
                mc, l, r1, r2
            });
        }
Exemplo n.º 14
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);
                }
            });
        }
        public static DataServicePackageRepository CreateDataServicePackageRepository(IHttpClient httpClient, TimeSpan timeout)
        {
            var userAgent = string.Format("{0}/{1} ({2})",
                                          UserAgent,
                                          typeof (MirroringPackageRepositoryFactory).Assembly.GetName().Version,
                                          Environment.OSVersion);

            var remoteRepository = new DataServicePackageRepository(httpClient);

            remoteRepository.SendingRequest += (s, e) =>
                {
                    e.Request.Timeout = (int) timeout.TotalMilliseconds;

                    ((HttpWebRequest) e.Request).UserAgent = userAgent;

                    e.Request.Headers.Add(RepositoryOperationNames.OperationHeaderName, RepositoryOperationNames.Mirror);
                };

            return remoteRepository;
        }
Exemplo n.º 16
0
        public static DataServicePackageRepository CreateDataServicePackageRepository(IHttpClient httpClient, TimeSpan timeout)
        {
            var userAgent = string.Format("{0}/{1} ({2})",
                                          UserAgent,
                                          typeof(MirroringPackageRepositoryFactory).Assembly.GetName().Version,
                                          Environment.OSVersion);

            var remoteRepository = new DataServicePackageRepository(httpClient);

            remoteRepository.SendingRequest += (s, e) =>
            {
                e.Request.Timeout = (int)timeout.TotalMilliseconds;

                ((HttpWebRequest)e.Request).UserAgent = userAgent;

                e.Request.Headers.Add(RepositoryOperationNames.OperationHeaderName, RepositoryOperationNames.Mirror);
            };

            return(remoteRepository);
        }
Exemplo n.º 17
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);
            }
        }
        private IPackage DownloadToMachineCache(
            IPackageCacheRepository cacheRepository,
            PackageIdentity package,
            DataServicePackageRepository repository,
            Uri downloadUri,
            NuGet.Common.ILogger logger,
            CancellationToken token)
        {
            var      packageName = new PackageNameWrapper(package);
            var      version     = SemanticVersion.Parse(package.Version.ToString());
            IPackage newPackage  = null;

            FileInfo   tmpFile       = null;
            FileStream tmpFileStream = null;

            // Create a v2 http client
            var downloadClient = new HttpClient(downloadUri)
            {
                UserAgent = UserAgent.UserAgentString
            };

            EventHandler <ProgressEventArgs> progressHandler = (sender, progress) =>
            {
                // Throw if this was canceled. This will stop the download.
                token.ThrowIfCancellationRequested();
            };

            Exception downloadException = null;

            Action <Stream> downloadAction = (stream) =>
            {
                try
                {
                    repository.PackageDownloader.ProgressAvailable += progressHandler;

                    repository.PackageDownloader.DownloadPackage(downloadClient, packageName, stream);
                }
                catch (Exception ex) when(ex is OperationCanceledException ||
                                          ex is IOException && ex.InnerException is SocketException)
                {
                    // The task was canceled. To avoid writing a partial file to the machine cache
                    // we need to clear out the current tmp file stream so that it will be ignored.
                    stream.SetLength(0);

                    // If the machine cache is using the physical file system we can find the
                    // path of temp file and clean it up. Otherwise NuGet.Core will just leave the temp file.
                    tmpFileStream = stream as FileStream;
                    if (tmpFileStream != null)
                    {
                        tmpFile = new FileInfo(tmpFileStream.Name);
                    }

                    downloadException = ex;
                }
                catch (Exception ex)
                {
                    downloadException = ex;
                }
                finally
                {
                    repository.PackageDownloader.ProgressAvailable -= progressHandler;
                }
            };

            // We either do not have a package available locally or they are invalid.
            // Download the package from the server.
            if (cacheRepository.InvokeOnPackage(package.Id, version,
                                                (stream) => downloadAction(stream)))
            {
                if (!token.IsCancellationRequested)
                {
                    newPackage = cacheRepository.FindPackage(package.Id, version);
                    Debug.Assert(newPackage != null);
                }
            }

            // After the stream is no longer in use, delete the tmp file
            // NuGet.Core does not properly clean these up since it does not have cancel support.
            if (tmpFile != null && token.IsCancellationRequested && tmpFile.Exists)
            {
                try
                {
                    tmpFile.Delete();
                }
                catch
                {
                    // Ignore exceptions for tmp file clean up
                }
            }

            if (downloadException != null)
            {
                throw downloadException;
            }

            return(newPackage);
        }
        private DownloadResourceResult DownloadFromIdentity(
            PackageIdentity identity,
            IPackageRepository repository,
            NuGet.Common.ILogger logger,
            CancellationToken token)
        {
            var version         = SemanticVersion.Parse(identity.Version.ToString());
            var dataServiceRepo = repository as DataServicePackageRepository;

            if (dataServiceRepo != null)
            {
                // Clone the repo to allow for concurrent calls
                var sourceUri = UriUtility.CreateSourceUri(dataServiceRepo.Source);
                dataServiceRepo = new DataServicePackageRepository(sourceUri);

                var package            = dataServiceRepo.FindPackage(identity.Id, version);
                var dataServicePackage = package as DataServicePackage;

                if (dataServicePackage != null)
                {
                    token.ThrowIfCancellationRequested();

                    // For online sources get the url and retrieve it with cancel support
                    var url = dataServicePackage.DownloadUrl;

                    var downloadedPackage = DownloadToMachineCache(
                        MachineCache.Default,
                        identity,
                        dataServiceRepo,
                        url,
                        logger,
                        token);

                    if (downloadedPackage != null)
                    {
                        return(new DownloadResourceResult(downloadedPackage.GetStream()));
                    }
                }
            }
            else
            {
                var package = repository.FindPackage(identity.Id, version);

                if (package != null)
                {
                    // Use a folder reader for unzipped repos
                    if (repository is UnzippedPackageRepository)
                    {
                        var packagePath   = Path.Combine(repository.Source, identity.Id + "." + version);
                        var directoryInfo = new DirectoryInfo(packagePath);
                        if (directoryInfo.Exists)
                        {
                            return(new DownloadResourceResult(
                                       package.GetStream(),
                                       new PackageFolderReader(directoryInfo)));
                        }
                    }

                    return(new DownloadResourceResult(package.GetStream()));
                }
            }

            return(new DownloadResourceResult(DownloadResourceResultStatus.NotFound));
        }
Exemplo n.º 20
0
 public Protocol2TestClient(Uri serverUri, string feed)
     : base(serverUri, feed)
 {
     packageServer     = new PackageServer(uri.ToString(), "");
     packageRepository = new DataServicePackageRepository(uri);
 }
Exemplo n.º 21
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);
                }
        }
Exemplo n.º 22
0
        private void LoadPackages()
        {
            StatusContent = "Connecting to package source...";

            TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            Task.Factory.StartNew <DataServicePackageRepository>(GetPackageRepository).ContinueWith(
                task => {
                DataServicePackageRepository repository = task.Result;
                if (repository == null)
                {
                    StatusContent = String.Empty;
                    ClearPackages();
                    return;
                }

                var query = repository.GetPackages();
                if (!String.IsNullOrEmpty(_currentSearch))
                {
                    query = query.Find(_currentSearch.Split(' '));
                }

                switch (SortColumn)
                {
                case "Id":
                    query = SortDirection == ListSortDirection.Descending ? query.OrderByDescending(p => p.Id) : query.OrderBy(p => p.Id);
                    break;

                case "Authors":
                    query = SortDirection == ListSortDirection.Descending ? query.OrderByDescending(p => p.Authors) : query.OrderBy(p => p.Authors);
                    break;

                case "VersionDownloadCount":
                    query = SortDirection == ListSortDirection.Descending ? query.OrderByDescending(p => p.VersionDownloadCount) : query.OrderBy(p => p.VersionDownloadCount);
                    break;

                case "Rating":
                    query = SortDirection == ListSortDirection.Descending ? query.OrderByDescending(p => p.VersionRating) : query.OrderBy(p => p.VersionRating);
                    break;

                default:
                    query = query.OrderByDescending(p => p.VersionDownloadCount);
                    break;
                }

                _currentQuery = query.Select(p => new PackageInfo {
                    Id                   = p.Id,
                    Version              = p.Version,
                    Authors              = p.Authors,
                    VersionRating        = p.VersionRating,
                    VersionDownloadCount = p.VersionDownloadCount,
                    PackageHash          = p.PackageHash
                });

                // every time the search query changes, we reset to page 0
                LoadPage(0);
            },
                CancellationToken.None,
                TaskContinuationOptions.OnlyOnRanToCompletion,
                uiScheduler
                );
        }