public void OnPackageOperationMessageLogged(NuGet.MessageLevel level, string message, params object[] args)
		{
			if (PackageOperationMessageLogged != null) {
				var eventArgs = new PackageOperationMessageLoggedEventArgs(level, message, args);
				PackageOperationMessageLogged(this, eventArgs);
			}
		}
		public void InstallPackage(string packageId, NuGet.SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
		{
			if (InstallPackageWithVersionCallback != null)
			{
				InstallPackageWithVersionCallback(packageId, version, ignoreDependencies, allowPrereleaseVersions);
			}
		}
Ejemplo n.º 3
0
        public void Execute_CallUninstallCommand_UninstallsNuGetPackage()
        {
            // arrange
            TestHelper.DeleteDirectoryIfExists("NuGetUnInstallTest");

            var target = new NuGet();
            WorkflowInvokerTest invoker = TestHelper.CreateWorkflowInvoker(target);

            var parameters = new Dictionary <string, object>
            {
                { "Command", NuGetCommand.Install },
                { "SourceRepository", new DirectoryInfo("TestData").FullName },
                { "LocalPath", "NuGetUnInstallTest" },
                { "PackageId", "MyPackage" },
                { "PackageVersion", "1.0.0" },
            };

            invoker.TestActivity(parameters);

            // act
            parameters["Command"]        = NuGetCommand.Uninstall;
            parameters["PackageVersion"] = "1.0.0";

            invoker.TestActivity(parameters);

            // assert
            invoker.AssertOutArgument.AreEqual("PackageInstallationPath", @"NuGetUnInstallTest\MyPackage.1.0.0");
            Assert.That(Directory.Exists(@"NuGetUnInstallTest\MyPackage.1.0.0"), Is.False);
        }
		public void InstallPackage(NuGet.IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
		{
			if (InstallPackageCallback != null)
			{
				InstallPackageCallback(package, ignoreDependencies, allowPrereleaseVersions);
			}
		}
Ejemplo n.º 5
0
 public void ExecuteOperation(NuGet.PackageOperation operation)
 {
     if (ExecuteOperationCallback != null)
     {
     	ExecuteOperationCallback(operation);
     }
 }
Ejemplo n.º 6
0
        public bool Exec(RestoreCommandOptions options)
        {
            bool ok;

            Toolchain.RequirePackDm(true);
            Toolchain.RequireSubversion(true);
            Toolchain.RequireNuGet(true);

            var pack = new Library.PackDm.PackDm();

            pack.PackConf = options.ConfFile.Text;
            pack.PackInfo = options.PackFile.Text;

            var svn   = new Svn();
            var nuget = new NuGet();

            ok = pack.Install();
            if (!ok)
            {
                return(Prompt.PrintCannotContinue());
            }

            ok = nuget.Restore();
            if (!ok)
            {
                return(Prompt.PrintCannotContinue());
            }

            ok = svn.Ignore("packages");

            return(true);
        }
Ejemplo n.º 7
0
        public void Log(NuGet.MessageLevel nugetLevel, string message, params object[] args)
        {
            EventType logLevel;
            if (!logLevels.TryGetValue(nugetLevel, out logLevel))
                logLevel = EventType.Error;

            _logger.Write(logLevel, message, args);
        }
 public static void Init(VCUtil vcutil,
                         NuGet nuget,
                         IVsProjectHelper projectHelper)
 {
     VCUtil        = vcutil;
     NuGet         = nuget;
     ProjectHelper = projectHelper;
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void packageManger_PackageInstalled(object sender, NuGet.PackageOperationEventArgs e)
        {
            //Copy the package files out to the correct locations
            e.Package.CopyPackageFiles();

            //If package has old format package.xml - lets try & improt doctypes & content etc...
            e.Package.InstallFromPackageXml();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Resolves the NuGet packages into assemblies to be referenced by the script.
        /// <para>If the package was never installed/downloaded yet CS-Script runtime will try to download it.</para>
        /// <para>CS-Script will also analyze the installed package structure in try to reference compatible assemblies
        /// from the package.</para>
        /// </summary>
        /// <param name="suppressDownloading">if set to <c>true</c> suppresses downloading the NuGet package.
        /// Suppressing can be useful for the quick 'referencing' assessment.</param>
        /// <returns>Collection of the referenced assembly files.</returns>
        public string[] ResolvePackages(bool suppressDownloading = false)
        {
#if !class_lib
            return(NuGet.Resolve(Packages, suppressDownloading, this.ScriptPath));
#else
            return(new string[0]);
#endif
        }
        static void Main(string[] args)
        {
            var nuGet = new NuGet(AppConfigurator.GetAppConfigurator());

            nuGet.Restore();

            // todo 支持更多命令
        }
Ejemplo n.º 12
0
 public NuGetReference(string packageId, NuGet.SemanticVersion version)
 {
     if (string.IsNullOrWhiteSpace(packageId))
     {
         throw new ArgumentNullException("packageId");
     }
     this.packageId = packageId;
     this.version = version;
 }
Ejemplo n.º 13
0
 public async Task LivePackagesAreIdentifiedCorrectly(string name, string version, bool live)
 {
     using (var http = new HttpClient())
     {
         NuGet nuget = new NuGet(http);
         var   ver   = Version.Parse(version);
         Assert.Equal(live, await nuget.IsPackageLiveAsync(name, ver, json));
     }
 }
Ejemplo n.º 14
0
 public void AddOperation(NuGet.PackageAction operationType, IPackage package, IProjectManager projectManager)
 {
     _operations.Add(new Operation()
     {
         OperationType = operationType,
         Package = package,
         ProjectManager = projectManager
     });
 }
        public PackageManagerControl(
            PackageManagerModel model, 
            NuGet.Configuration.ISettings nugetSettings, 
            IVsWindowSearchHostFactory searchFactory)
        {
            _uiDispatcher = Dispatcher.CurrentDispatcher;
            Model = model;
            if (Model.Context.Projects.Count() == 1)
            {
                _detailModel = new PackageDetailControlModel(Model.Context.Projects);
            }
            else
            {
                _detailModel = new PackageSolutionDetailControlModel(Model.Context.Projects);
            }

            InitializeComponent();
            SetStyles();

            _windowSearchHostFactory = searchFactory;
            if (_windowSearchHostFactory != null)
            {
                _windowSearchHost = _windowSearchHostFactory.CreateWindowSearchHost(_searchControlParent);
                _windowSearchHost.SetupSearch(this);
                _windowSearchHost.IsVisible = true;
            }

            AddRestoreBar();

            _packageDetail.Control = this;
            _packageDetail.Visibility = Visibility.Hidden;

            SetTitle();

            var settings = LoadSettings();
            InitializeFilterList(settings);
            InitSourceRepoList(settings);
            ApplySettings(settings, nugetSettings);

            _initialized = true;

            // register with the UI controller
            NuGetUI controller = model.UIController as NuGetUI;
            if (controller != null)
            {
                controller.PackageManagerControl = this;
            }

            Model.Context.SourceProvider.PackageSourceProvider.PackageSourcesSaved += Sources_PackageSourcesChanged;

            if (IsUILegalDisclaimerSuppressed())
            {
                _legalDisclaimer.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
 public NuGet.IPackageRepository GetRepositoryFromSource(NuGet.PackageSource packageSource)
 {
     if (GetRepositoryFromSourceCallback != null)
     {
         return GetRepositoryFromSourceCallback(packageSource);
     }
     else
     {
         return null;
     }
 }
Ejemplo n.º 17
0
        void launcher_ProgressAvailable(object sender, NuGet.ProgressEventArgs e)
        {
            loadingMessage = string.Format("{0} ({1}%)", e.Operation, e.PercentComplete);

            if (IsDisposed || !launcher.IsDownloading)
            {
                return;
            }

            tempLogEvents.Enqueue(new NugetLogEventArgs(MessageLevel.Info, loadingMessage));
        }
        static void Main(string[] args)
        {
            var appConfigurator = AppConfigurator.GetAppConfigurator();
            var nuGet           = new NuGet(appConfigurator);

            Log.Info($"当前命令行 {Environment.CommandLine}");

            if (args.Length == 1)
            {
                // 可以传入命令行或文件
                if (Directory.Exists(args[0]))
                {
                    Log.Info($"传入 NuGet 文件所在文件夹 {args[0]}");
                    appConfigurator.Of <CompileConfiguration>().NupkgDirectory = args[0];
                    nuGet.PublishNupkg();
                }
                else if (File.Exists(args[0]))
                {
                    Log.Info($"传入 NuGet 文件 {args[0]}");
                    nuGet.PublishNupkg(new FileInfo(args[0]));
                }
                else if (args[0] == "-h" || args[0] == "--help")
                {
                    Console.WriteLine(@"此命令用于将 NuGet 包发布到配置的默认源,默认将会取 Compile.NupkgDirectory 文件夹内的 nupkg 文件上传到 Nuget.Source 服务器
命令可不填写参数,不填写时将会使用配置的 Compile.NupkgDirectory 文件夹内的所有 nupkg 文件上传
命令可选参数是 nupkg 文件路径或文件所在文件夹

NuGetPublishTask [nupkg file path | nupkg folder]

NuGetPublishTask [nupkg 文件路径 | nupkg 文件所在文件夹]

如需指定非配置里面的 NuGet 服务器等,请直接使用 nuget 命令");
                    return;
                }
                else
                {
                    Log.Error($"未能解析传入内容为 NuGet 文件或所在文件夹");
                    Environment.Exit(-1);
                    return;
                }
            }
            else if (args.Length == 0)
            {
                nuGet.PublishNupkg();
            }
            else
            {
                Log.Error("此命令仅接受传入当前 NuGet 包文件路径或所在文件夹,此命令用于将 NuGet 包发布到配置的默认源");
                Environment.Exit(-1);
                return;
            }
        }
Ejemplo n.º 19
0
        public void NuGetConfigIsGeneratedCorrectly(string[] urls, string feedParts)
        {
            using (var http = new HttpClient())
            {
                NuGet nuget = new NuGet(http);

                var expectedConfig        = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <configuration> <packageSources> " + feedParts + " </packageSources> </configuration>";
                var cleanedExpectedConfig = Regex.Replace(expectedConfig, @"\s+", " ");

                var actualConfig        = nuget.GenerateNuGetConfig(urls.ToList());
                var cleanedActualConfig = Regex.Replace(actualConfig, @"\s+", " ");

                Assert.Equal(cleanedExpectedConfig, cleanedActualConfig);
            }
        }
        /// <inheritdoc />
        public Compiler(IAppConfigurator appConfigurator = null, ILogger logger = null) : base(appConfigurator, logger)
        {
            _appConfigurator = appConfigurator;

            Init();

            Nuget = new NuGet(AppConfigurator);
#pragma warning disable CS0618
            MsBuild = new MsBuild(AppConfigurator);
#pragma warning restore CS0618
            MSBuild    = new MSBuild(AppConfigurator);
            TestHelper = new TestHelper(AppConfigurator);

            //_logger = logger ?? AppConfigurator.Of<LogConfiguration>().GetLogger();
        }
Ejemplo n.º 21
0
        public Project(
            string solutionDirPath,
            string targetProjectFile)
        {
            // process solution dir path

            if (string.IsNullOrEmpty(solutionDirPath))
            {
                throw new ArgumentException("solutionDirPath cannot be a null or empty string");
            }

            if (!Directory.Exists(solutionDirPath))
            {
                throw new ArgumentException(string.Format("solutionDirPath does not exist, \"{0}\"", solutionDirPath));
            }

            SolutionDirPath = solutionDirPath;

            // process target project file

            if (string.IsNullOrEmpty(targetProjectFile))
            {
                throw new ArgumentException("targetProjectFile cannot be a null or empty string");
            }

            if (!File.Exists(targetProjectFile))
            {
                throw new ArgumentException(string.Format("targetProjectFile does not exist, \"{0}\"", targetProjectFile));
            }

            TargetProjectFile = targetProjectFile;

            // set project directory path

            TargetProjectDirectoryPath = Path.GetDirectoryName(TargetProjectFile);
            if (string.IsNullOrEmpty(TargetProjectDirectoryPath))
            {
                throw new InvalidOperationException(string.Format("Could not get directory path from TargetProjectFile, \"{0}\"", TargetProjectFile));
            }

            // instantiate components

            AssemblyInfo = new AssemblyInfo(SolutionDirPath, TargetProjectFile);
            MsBuild      = new MsBuild(TargetProjectFile);
            NuGet        = new NuGet(TargetProjectFile);
        }
Ejemplo n.º 22
0
 public void InitializeProjects(List <IVsProject> projects)
 {
     try
     {
         NuGet.OnNugetBatchEnd(null);
         ProjectConverter.TryUpgrade(projects);
         projects = DTEUtil.GetProjects();
         foreach (IVsProject project in projects)
         {
             InitializeProject(project);
         }
     }
     finally
     {
         NuGet.OnNugetBatchEnd(PackageInstalled);
     }
 }
 public SolutionDriver(NuGetConfigGenerator nuGetConfigGenerator, TestRunConfiguration testRunConfiguration, ProjectBuilderFactory projectBuilderFactory, Folders folders, NuGet nuGet, TestProjectFolders testProjectFolders, Compiler compiler, IOutputWriter outputWriter)
 {
     _nuGetConfigGenerator  = nuGetConfigGenerator;
     _testRunConfiguration  = testRunConfiguration;
     _projectBuilderFactory = projectBuilderFactory;
     _folders            = folders;
     _nuGet              = nuGet;
     _testProjectFolders = testProjectFolders;
     _compiler           = compiler;
     _outputWriter       = outputWriter;
     NuGetSources        = new List <NuGetSource>
     {
         new NuGetSource("LocalSpecFlowDevPackages", _folders.NuGetFolder),
         new NuGetSource("SpecFlow CI", "https://www.myget.org/F/specflow/api/v3/index.json")
     };
     _solution = new Solution(SolutionName);
     testProjectFolders.PathToSolutionFile = Path.Combine(_folders.FolderToSaveGeneratedSolutions, SolutionName, $"{SolutionName}.sln");
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates manifest file for theme or widget to save package metadata
        /// </summary>
        /// <param name="package">Package</param>
        /// <param name="packageFiles">Installed files</param>
        public static void CreateManifestIfNotExists(NuGet.IPackage package, List<PackageFile> packageFiles)
        {
            var shortPath = "";
            var type = PackageType(packageFiles);

            if (type == "theme")
                shortPath = string.Format(@"Custom\Themes\{0}\theme.xml", package.Id);

            if (type == "widget")
                shortPath = string.Format(@"Custom\Widgets\{0}\widget.xml", package.Id);

            if (string.IsNullOrEmpty(shortPath))
                return;

            var path = Path.Combine(HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot), shortPath);

            if (File.Exists(path))
                return;

            using (var writer = new XmlTextWriter(path, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 4;
                writer.WriteStartDocument(true);
                writer.WriteStartElement("metadata");

                writer.WriteElementString("id", package.Id);
                writer.WriteElementString("description", package.Description);

                writer.WriteElementString("authors", string.Join(", ", package.Authors));

                writer.WriteElementString("website", package.ProjectUrl == null ? "" : package.ProjectUrl.ToString());
                writer.WriteElementString("version", package.Version.ToString());
                writer.WriteElementString("iconurl", package.IconUrl == null ? "" : package.IconUrl.ToString());

                writer.WriteEndElement();
            }
            var idx = packageFiles.Count + 1;
            packageFiles.Add(new PackageFile { PackageId = package.Id, FileOrder = idx, FilePath = shortPath, IsDirectory = false });
        }
Ejemplo n.º 25
0
        private async Task EnsureNuGetPackages()
        {
            var nugetVariable    = MainViewModel.NuGetConfiguration.PathVariableName;
            var pathToRepository = MainViewModel.NuGetConfiguration.PathToRepository;

            foreach (var directive in MainViewModel.RoslynHost.GetReferencesDirectives(DocumentId))
            {
                if (directive.StartsWith(nugetVariable, StringComparison.OrdinalIgnoreCase))
                {
                    var directiveWithoutRoot = directive.Substring(nugetVariable.Length + 1);
                    if (!File.Exists(Path.Combine(pathToRepository, directiveWithoutRoot)))
                    {
                        var          sections = directiveWithoutRoot.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                        NuGetVersion version;
                        if (sections.Length > 2 && NuGetVersion.TryParse(sections[1], out version))
                        {
                            await NuGet.InstallPackage(sections[0], version, reportInstalled : false).ConfigureAwait(false);
                        }
                    }
                }
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Inserts a dependency set into the packagebuilder object, based on a dictionary
        /// containing Id/version pairs (Newtonsoft.json, 5.0.6 for example).
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="packages"></param>
        private void AddNugetDependencies(NuGet.PackageBuilder builder, Dictionary<string, string> packages)
        {
            //add dependencies
              List<PackageDependency> dependencies = new List<PackageDependency>();
              foreach (var package in packages)
              {
              dependencies.Add(new PackageDependency(package.Key, new VersionSpec {MinVersion = new SemanticVersion(package.Value), IsMinInclusive = true}));
              }

              var set = new PackageDependencySet(null, dependencies);
              builder.DependencySets.Add(set);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Adds project references to the package lib section
 /// </summary>
 /// <param name="builder">
 /// The current package builder
 /// </param>
 private void AddLibraries(NuGet.PackageBuilder builder)
 {
     // add package files from project references
      // . DLL references go in the lib package folder
      // . EXE references go in the tools package folder
      // . everything else goes in the content package folder
      // . folders may be overridden using NuBuildTargetFolder metadata (lib\net40, etc.)
      // . folders may be overridden using TargetFramework attribute (lib\net40, etc.)
      foreach (var libItem in this.ReferenceLibraries)
      {
     var srcPath = libItem.GetMetadata("FullPath");
     var srcExt = Path.GetExtension(srcPath).ToLower();
     var tgtFolder = "content";
     var hasPdb = false;
     if (srcExt == ".dll")
     {
        tgtFolder = "lib";
        hasPdb = true;
     }
     else if (srcExt == ".exe")
     {
        tgtFolder = "tools";
        hasPdb = true;
     }
     // apply the custom folder override on the reference, or based on TargetFramework
     var customFolder = libItem.GetMetadata("NuBuildTargetFolder");
     if (!String.IsNullOrWhiteSpace(customFolder))
        tgtFolder = customFolder;
     else if (AddBinariesToSubfolder)
        try
        {
           var targetFrameworkName = AssemblyReader.Read(srcPath).TargetFrameworkName;
           if (!String.IsNullOrWhiteSpace(targetFrameworkName))
              tgtFolder = Path.Combine(tgtFolder, VersionUtility.GetShortFrameworkName(new FrameworkName(targetFrameworkName)));
        }
        catch { }
     // add the source library file to the package
     builder.Files.Add(
        new NuGet.PhysicalPackageFile()
        {
           SourcePath = srcPath,
           TargetPath = String.Format(
              @"{0}\{1}",
              tgtFolder,
              Path.GetFileName(srcPath)
           )
        }
     );
     // add PDBs if specified and exist
     if (hasPdb && this.IncludePdbs)
     {
        var pdbPath = Path.ChangeExtension(srcPath, ".pdb");
        if (File.Exists(pdbPath))
           builder.Files.Add(
              new NuGet.PhysicalPackageFile()
              {
                 SourcePath = pdbPath,
                 TargetPath = String.Format(
                    @"{0}\{1}",
                    tgtFolder,
                    Path.GetFileName(pdbPath)
                 )
              }
           );
     }
      }
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Go through each referenced project, and add any nuget dependencies from 
        /// their packages.config file.  Ignores any that have developerDependency=true
        /// </summary>
        /// <param name="builder"></param>
        private void AddDependencies(NuGet.PackageBuilder builder)
        {
            Dictionary<string, string> NugetPackages = new Dictionary<string, string>();

              string projectRoot = Path.GetDirectoryName(this.ProjectPath);

              XElement root = XElement.Load(this.ProjectPath);
              var ns = root.Name.Namespace;
              var elems = (from el in root.Descendants(ns + "ProjectReference")
              select el).ToList();

              if (elems.Any())
              {
              foreach (var item in elems)
              {
                  string itemPath = item.Attribute("Include").Value;
                  string packagesPath = Path.GetFullPath(Path.Combine(projectRoot, Path.GetDirectoryName(itemPath))) +  Path.DirectorySeparatorChar + PACKAGES_CONFIG;
                  GetNuGetDependencies(packagesPath, NugetPackages);
              }
              }

              if (NugetPackages.Any())
              AddNugetDependencies(builder, NugetPackages);
        }
Ejemplo n.º 29
0
 public bool PackageContainsAddIn(NuGet.IPackage package)
 {
     return FakePackageContainsAddIn;
 }
Ejemplo n.º 30
0
        protected override async Task InitializeAsync(CancellationToken cancel,
                                                      IProgress <Microsoft.VisualStudio.Shell.ServiceProgressData> progress)
        {
            Instance = this;
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            AutoBuilding = GetAutoBuilding();

            object value = null;

            {
                Shell = await GetServiceAsync(typeof(IVsShell)) as IVsShell;

                if (Shell == null)
                {
                    throw new PackageInitializationException("Error initializing Shell");
                }
                Shell.GetProperty((int)__VSSPROPID.VSSPROPID_IsInCommandLineMode, out value);
                CommandLineMode = (bool)value;
            }

            if (!CommandLineMode)
            {
                InstallDirectory   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                ResourcesDirectory = Path.Combine(InstallDirectory, "Resources");

                DTE2 = await GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;

                if (DTE2 == null)
                {
                    throw new PackageInitializationException("Error initializing DTE2");
                }

                DTEEvents = DTE.Events.DTEEvents;

                IVsSolution = await GetServiceAsync(typeof(SVsSolution)) as IVsSolution;

                if (IVsSolution == null)
                {
                    throw new PackageInitializationException("Error initializing IVsSolution");
                }

                IVsSolution4 = await GetServiceAsync(typeof(SVsSolution)) as IVsSolution4;

                if (IVsSolution4 == null)
                {
                    throw new PackageInitializationException("Error initializing IVsSolution4");
                }

                UIShell = await GetServiceAsync(typeof(SVsUIShell)) as IVsUIShell;

                if (UIShell == null)
                {
                    throw new PackageInitializationException("Error initializing UIShell");
                }

                MonitorSelection = await GetServiceAsync(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;

                if (MonitorSelection == null)
                {
                    throw new PackageInitializationException("Error initializing MonitorSelection");
                }

                //
                // Update the InstallDir this was previously used in project imports, but is still usefull if you
                // need to detect the extension install dir.
                //
                Registry.SetValue(IceBuilderKey, string.Format("InstallDir.{0}", DTE.Version), InstallDirectory,
                                  RegistryValueKind.String);

                Assembly assembly = null;
                if (DTE.Version.StartsWith("14.0"))
                {
                    assembly = Assembly.LoadFrom(Path.Combine(ResourcesDirectory, "IceBuilder.VS2015.dll"));
                }
                else if (DTE.Version.StartsWith("15.0"))
                {
                    assembly = Assembly.LoadFrom(Path.Combine(ResourcesDirectory, "IceBuilder.VS2017.dll"));
                }
                else
                {
                    assembly = Assembly.LoadFrom(Path.Combine(ResourcesDirectory, "IceBuilder.VS2019.dll"));
                }
                var factory = assembly.GetType("IceBuilder.ProjectHelperFactoryI").GetConstructor(new Type[] { }).Invoke(
                    new object[] { }) as IVsProjectHelperFactory;

                VCUtil        = factory.VCUtil;
                NuGet         = factory.NuGet;
                ProjectHelper = factory.ProjectHelper;

                ProjectFactoryHelperInstance.Init(VCUtil, NuGet, ProjectHelper);

                NuGet.OnNugetBatchEnd(PackageInstalled);

                RunningDocumentTableEventHandler = new RunningDocumentTableEventHandler(
                    await GetServiceAsync(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable);

                Builder = new Builder(await GetServiceAsync(typeof(SVsBuildManagerAccessor)) as IVsBuildManagerAccessor2);

                //
                // Subscribe to solution events.
                //
                SolutionEventHandler = new SolutionEventHandler();
                SolutionEventHandler.BeginTrack();

                DocumentEventHandler = new DocumentEventHandler(
                    await GetServiceAsync(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2);
                DocumentEventHandler.BeginTrack();

                BuildEvents = DTE2.Events.BuildEvents;
                BuildEvents.OnBuildBegin += BuildEvents_OnBuildBegin;
                BuildEvents.OnBuildDone  += BuildEvents_OnBuildDone;
            }

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            RegisterProjectFactory(new ProjectFactory());
            RegisterProjectFactory(new ProjectFactoryOld());

            value = null;
            IVsSolution.GetProperty((int)__VSPROPID.VSPROPID_IsSolutionOpen, out value);
            if ((bool)value)
            {
                RunningDocumentTableEventHandler.BeginTrack();
                InitializeProjects(DTEUtil.GetProjects());
            }
        }
Ejemplo n.º 31
0
 public void Test1()
 {
     Assert.Equal($@"{NuGet.PackagesPath}def.test\1.0.0\", NuGet.PackageFolder(Assembly.GetExecutingAssembly()));
 }
 public OldProjectFormatNuGetRestorer(NuGet nuget)
 {
     _nuget = nuget;
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Resolves the NuGet packages into assemblies to be referenced by the script.
        /// <para>If the package was never installed/downloaded yet CS-Script runtime will try to download it.</para>
        /// <para>CS-Script will also analyze the installed package structure in try to reference compatible assemblies
        /// from the package.</para>
        /// </summary>
        /// <param name="suppressDownloading">if set to <c>true</c> suppresses downloading the NuGet package.
        /// Suppressing can be useful for the quick 'referencing' assessment.</param>
        /// <returns>Collection of the referenced assembly files.</returns>
        public string[] ResolvePackages(bool suppressDownloading = false)
#endif
        {
            return(NuGet.Resolve(Packages, suppressDownloading, this.ScriptPath));
        }
Ejemplo n.º 34
0
        protected override void Initialize()
        {
            base.Initialize();
            Instance = this;

            AutoBuilding = GetAutoBuilding();

            {
                Shell = GetService(typeof(IVsShell)) as IVsShell;
                object value;
                Shell.GetProperty((int)__VSSPROPID.VSSPROPID_IsInCommandLineMode, out value);
                CommandLineMode = (bool)value;
            }

            RegisterProjectFactory(new ProjectFactory());
            RegisterProjectFactory(new ProjectFactoryOld());

            if (!CommandLineMode)
            {
                InstallDirectory   = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                ResourcesDirectory = Path.Combine(InstallDirectory, "Resources");

                DTE2             = (EnvDTE80.DTE2)GetService(typeof(EnvDTE.DTE));
                DTEEvents        = DTE.Events.DTEEvents;
                IVsSolution      = GetService(typeof(SVsSolution)) as IVsSolution;
                IVsSolution4     = GetService(typeof(SVsSolution)) as IVsSolution4;
                UIShell          = Instance.GetService(typeof(SVsUIShell)) as IVsUIShell;
                MonitorSelection = GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;

                //
                // Update the InstallDir this was previously used in project imports, but is still usefull if you
                // need to detect the extension install dir.
                //
                Registry.SetValue(IceBuilderKey, string.Format("InstallDir.{0}", DTE.Version), InstallDirectory,
                                  RegistryValueKind.String);

                Assembly assembly = null;
                if (DTE.Version.StartsWith("11.0"))
                {
                    assembly = Assembly.LoadFrom(Path.Combine(ResourcesDirectory, "IceBuilder.VS2012.dll"));
                }
                else if (DTE.Version.StartsWith("12.0"))
                {
                    assembly = Assembly.LoadFrom(Path.Combine(ResourcesDirectory, "IceBuilder.VS2013.dll"));
                }
                else if (DTE.Version.StartsWith("14.0"))
                {
                    assembly = Assembly.LoadFrom(Path.Combine(ResourcesDirectory, "IceBuilder.VS2015.dll"));
                }
                else
                {
                    assembly = Assembly.LoadFrom(Path.Combine(ResourcesDirectory, "IceBuilder.VS2017.dll"));
                }
                VCUtil = assembly.GetType("IceBuilder.VCUtilI").GetConstructor(new Type[] { }).Invoke(
                    new object[] { }) as VCUtil;

                NuGet = assembly.GetType("IceBuilder.NuGetI").GetConstructor(new Type[] { }).Invoke(
                    new object[] { }) as IceBuilder.NuGet;
                NuGet.OnNugetBatchEnd(PackageInstalled);

                ProjectManagerFactory = assembly.GetType("IceBuilder.ProjectManagerFactoryI").GetConstructor(new Type[] { }).Invoke(
                    new object[] { }) as IVsProjectManagerFactory;

                RunningDocumentTableEventHandler = new RunningDocumentTableEventHandler(
                    GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable);

                Builder = new Builder(GetService(typeof(SVsBuildManagerAccessor)) as IVsBuildManagerAccessor2);

                //
                // Subscribe to solution events.
                //
                SolutionEventHandler = new SolutionEventHandler();
                SolutionEventHandler.BeginTrack();

                DocumentEventHandler = new DocumentEventHandler(
                    GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2);
                DocumentEventHandler.BeginTrack();

                FileTracker = new GeneratedFileTracker();

                BuildEvents = DTE2.Events.BuildEvents;
                BuildEvents.OnBuildBegin += BuildEvents_OnBuildBegin;
                BuildEvents.OnBuildDone  += BuildEvents_OnBuildDone;
            }
        }
Ejemplo n.º 35
0
 public ICSharpCode.Core.AddIn InstallAddIn(NuGet.IPackage package, string packageDirectory)
 {
     if (InstallAddInFromArchiveCallback != null)
        	{
        		return InstallAddInFromPackageCallback(package, packageDirectory);
        	}
        	else
        	{
        		return null;
        	}
 }
Ejemplo n.º 36
0
 public ICSharpCode.Core.AddIn GetAddInForNuGetPackage(NuGet.IPackage package)
 {
     return GetAddInForNuGetPackage(package, false);
 }
Ejemplo n.º 37
0
 public NuGetRestorerFactory(NuGet nuget)
 {
     _nuget = nuget;
 }
Ejemplo n.º 38
0
 public void Test2()
 {
     Assert.Equal($@"{NuGet.PackagesPath}def\1.2.3.4\", NuGet.PackageFolder("def", new Version(1, 2, 3, 4)));
     Assert.Equal($@"{NuGet.PackagesPath}def\1.2.3\", NuGet.PackageFolder("def", new Version(1, 2, 3)));
     Assert.Equal($@"{NuGet.PackagesPath}def\1.2.0\", NuGet.PackageFolder("def", new Version(1, 2)));
 }
Ejemplo n.º 39
0
        private Dictionary<string, string> CreateFileMapping(NuGet.IPackage package)
        {
            Dictionary<string,string> fileMapping = new Dictionary<string,string>();

            bool isDualityPackage =
                package.Tags != null &&
                package.Tags.Contains("Duality");
            bool isPluginPackage =
                isDualityPackage &&
                package.Tags.Contains("Plugin");
            string binaryBaseDir = this.pluginTargetDir;
            string contentBaseDir = this.dataTargetDir;
            if (!isPluginPackage || !isDualityPackage) binaryBaseDir = "";

            foreach (var f in package.GetFiles()
                .Where(f => f.TargetFramework == null || f.TargetFramework.Version < Environment.Version)
                .OrderByDescending(f => f.TargetFramework == null ? new Version() : f.TargetFramework.Version)
                .OrderByDescending(f => f.TargetFramework == null))
            {
                // Determine where the file needs to go
                string targetPath = f.EffectivePath;
                string baseDir = f.Path;
                while (baseDir.Contains(Path.DirectorySeparatorChar) || baseDir.Contains(Path.AltDirectorySeparatorChar))
                {
                    baseDir = Path.GetDirectoryName(baseDir);
                }
                if (string.Equals(baseDir, "lib", StringComparison.InvariantCultureIgnoreCase))
                    targetPath = Path.Combine(binaryBaseDir, targetPath);
                else if (string.Equals(baseDir, "content", StringComparison.InvariantCultureIgnoreCase))
                    targetPath = Path.Combine(contentBaseDir, targetPath);
                else
                    continue;

                // Add a file mapping entry linking target path to package path
                if (fileMapping.ContainsKey(targetPath)) continue;
                fileMapping[targetPath] = f.Path;
            }

            return fileMapping;
        }
Ejemplo n.º 40
0
 public void PreviewTest()
 {
     Assert.Equal($@"{NuGet.PackagesPath}def\1.2.3.4-alpha\", NuGet.PackageFolder("def", new Version(1, 2, 3, 4), "alpha"));
     Assert.Equal($@"{NuGet.PackagesPath}def\1.2.3-alpha\", NuGet.PackageFolder("def", new Version(1, 2, 3), "alpha"));
     Assert.Equal($@"{NuGet.PackagesPath}def\1.2.0-alpha\", NuGet.PackageFolder("def", new Version(1, 2), "alpha"));
 }
Ejemplo n.º 41
0
        private PackageInfo CreatePackageInfo(NuGet.IPackage package)
        {
            PackageInfo info = new PackageInfo(package.Id, package.Version.Version);

            info.Title			= package.Title;
            info.Summary		= package.Summary;
            info.Description	= package.Description;
            info.ProjectUrl		= package.ProjectUrl;
            info.IconUrl		= package.IconUrl;
            info.DownloadCount	= package.DownloadCount;
            info.PublishDate	= package.Published.HasValue ? package.Published.Value.DateTime : DateTime.MinValue;
            info.Authors		= package.Authors;
            info.Tags			= package.Tags != null ? package.Tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) : Enumerable.Empty<string>();

            return info;
        }
Ejemplo n.º 42
0
        private static string GetOutputPath(NuGet.PackageBuilder builder, string outputDirectory)
        {
            string version = builder.Version.ToString();

            // Output file is {id}.{version}
            string outputFile = builder.Id + "." + version;
            outputFile += NuGet.Constants.PackageExtension;

            return Path.Combine(outputDirectory, outputFile);
        }
Ejemplo n.º 43
0
 public override IVsExtension CreateExtension(NuGet.IPackage package)
 {
     return new PackageItem(this, package);
 }
Ejemplo n.º 44
0
        public int CompareAddInToPackageVersion(ICSharpCode.Core.AddIn addIn, NuGet.IPackage nuGetPackage)
        {
            if ((addIn == null) || (nuGetPackage == null))
            {
                // Consider this as equal (?)
                return 0;
            }

            // Look if AddIn has a NuGet version tag in manifest
            Version addInVersion = addIn.Version;
            if (addIn.Properties.Contains(ManagedAddIn.NuGetPackageVersionManifestAttribute))
            {
                try
                {
                    addInVersion = new Version(addIn.Properties[ManagedAddIn.NuGetPackageVersionManifestAttribute]);
                }
                catch (Exception)
                {
                    addInVersion = addIn.Version;
                }
            }

            if (addInVersion == null)
            {
                if (nuGetPackage == null)
                {
                    // Both versions are null -> equal
                    return 0;
                }
                else
                {
                    // Non-null version is greater
                    return -1;
                }
            }

            return addInVersion.CompareTo(nuGetPackage.Version.Version);
        }
Ejemplo n.º 45
0
        public void Consume(DeployMessage message)
        {
            var outputDirectory = (Environment.GetEnvironmentVariable("DagentPackagesPath") ?? @"C:\Program Files\Dagent\Packages\");

            if (Directory.Exists(outputDirectory))
            {
                Directory.Delete(outputDirectory, true);
            }
            Directory.CreateDirectory(outputDirectory);
            //
            string body;

            using (var context = _hostingSection.MakeDeployContextByID(message.ApiKey))
                if (context != null)
                {
                    var    b = new StringBuilder();
                    string packagesDirectory = null;
                    try
                    {
                        string arg0;
                        string version;
                        if (message.FromSpec)
                        {
                            InstallPackagesFromConfigFile(message.Items, out packagesDirectory, out arg0, out version);
                        }
                        else
                        {
                            InstallPackagesInline(message.Items, out arg0, out version);
                        }
                        // install
                        NuGet.NuMain(b, null, m =>
                        {
                            var command = (DeployLocalCommand)m.GetCommands().FirstOrDefault(x => x is DeployLocalCommand);
                            if (command == null)
                            {
                                throw new NullReferenceException("Unable to find DeployInstallCommand");
                            }
                            command.Prerelease     = message.Prerelease;
                            command.ExcludeVersion = message.ExcludeVersion;
                            command.Version        = version;
                            command.Source.Add("http://nuget.degdarwin.com/nuget");
                            //command.Source.Add("http://nuget.degdarwin.com/Dagent/nuget");
                            command.OutputDirectory = outputDirectory;
                            command.Project         = message.Project;
                            command.Arguments.Add(arg0);
                            return(command);
                        });
                    }
                    catch (Exception ex)
                    {
                        b.AppendLine(ex.Message);
                        b.AppendLine();
                        b.AppendLine(ex.StackTrace);
                    }
                    finally { if (packagesDirectory != null && Directory.Exists(packagesDirectory))
                              {
                                  Directory.Delete(packagesDirectory, true);
                              }
                    }
                    body = b.ToString();
                }
                else
                {
                    body = "Incorrect Application Key " + message.ApiKey;
                }
            // notification
            var notification = _appSection.Notification;

            if (_appSection.HasNotification && notification != null && !string.IsNullOrEmpty(message.Email))
            {
                notification.SendEmail(message.Email, string.Format(notification.Subject, message.Project), body);
            }
        }
Ejemplo n.º 46
0
 public ICSharpCode.Core.AddIn GetAddInForNuGetPackage(NuGet.IPackage package, bool withAddInsMarkedForInstallation)
 {
     if (GetAddInForNuGetPackageCallback != null)
        	{
        		return GetAddInForNuGetPackageCallback(package, withAddInsMarkedForInstallation);
        	}
        	else
        	{
        		return null;
        	}
 }
Ejemplo n.º 47
0
 public IPackagePathResolver get_path_resolver(NuGet.IFileSystem nugetPackagesFileSystem)
 {
     return new DefaultPackagePathResolver(nugetPackagesFileSystem)
     {
     };
 }
Ejemplo n.º 48
0
        public IPackageRepository get_local_repository(IPackagePathResolver pathResolver, NuGet.IFileSystem nugetPackagesFileSystem)
        {
            this.Log().Debug(() => "Setting up local repository at '{0}'".format_with(nugetPackagesFileSystem.Root));

            IPackageRepository localRepository = new LocalPackageRepository(pathResolver, nugetPackagesFileSystem);
            localRepository.PackageSaveMode = PackageSaveModes.Nupkg | PackageSaveModes.Nuspec;

            return localRepository;
        }
Ejemplo n.º 49
0
        void DownloadPackage(IPackage package, string fullPathToDownloadTo, NuGet.PackageDownloader directDownloader)
        {
            Log.VerboseFormat("Found package {0} version {1}", package.Id, package.Version);
            Log.Verbose("Downloading to: " + fullPathToDownloadTo);

            var dsp = package as DataServicePackage;
            if (dsp != null && directDownloader != null)
            {
                Log.Verbose("A direct download is possible; bypassing the NuGet machine cache");
                using (var targetFile = new FileStream(fullPathToDownloadTo, FileMode.CreateNew))
                    directDownloader.DownloadPackage(dsp.DownloadUrl, dsp, targetFile);
                return;
            }

            var physical = new PhysicalFileSystem(Path.GetDirectoryName(fullPathToDownloadTo));
            var local = new LocalPackageRepository(new FixedFilePathResolver(package.Id, fullPathToDownloadTo), physical);
            local.AddPackage(package);
        }
		static string ConvertToString (NuGet.Configuration.PackageSource source)
		{
			if (source != null) {
				return String.Format ("[PackageSource] Name='{0}', Source='{1}'",
					source.Name,
					source.Source);
			}
			return "[PackageSource] == Null";
		}
Ejemplo n.º 51
0
        IPackage FindPackage(int attempt, string packageId, string packageVersion, string feed, out NuGet.PackageDownloader downloader)
        {
            Log.VerboseFormat("Finding package (attempt {0} of {1})", attempt, NumberOfTimesToAttemptToDownloadPackage);

            var remoteRepository = packageRepositoryFactory.CreateRepository(feed);

            var dspr = remoteRepository as DataServicePackageRepository;
            downloader = dspr != null ? dspr.PackageDownloader : null;

            var requiredVersion = new SemanticVersion(packageVersion);
            var package = remoteRepository.FindPackage(packageId, requiredVersion, true, true);

            if (package == null)
                throw new Exception(string.Format("Could not find package {0} {1} in feed: '{2}'", packageId, packageVersion, feed));

            if (!requiredVersion.Equals(package.Version))
            {
                var message = string.Format("The package version '{0}' returned from the package repository doesn't match the requested package version '{1}'.", package.Version, requiredVersion);
                throw new Exception(message);
            }

            return package;
        }
		protected override bool IsProjectPackage(NuGet.IPackage package)
		{
			IsProjectPackageIsCalled = true;
			return IsProjectPackageReturnsValue;
		}
        protected (bool success, string output) NuGetRestore(string command = "")
        {
            var nuGet = new NuGet(AppConfigurator);

            return(nuGet.Restore(command));
        }