コード例 #1
0
        /////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            packageInstaller     = ComponentModel.GetService <IVsPackageInstaller>();
            pkgInstallerServices = ComponentModel.GetService <IVsPackageInstallerServices>();
            base.Initialize();

            _outputWindow = new OutputWindowWriter(this, GuidList.guidServiceStackVSOutputWindowPane, "ServiceStackVS");

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (null != mcs)
            {
                // Create the command for the menu item.
                CommandID cSharpProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidServiceStackReference);
                var       cSharpProjectContextOleMenuCommand     = new OleMenuCommand(CSharpAddReferenceCallback, cSharpProjContextAddReferenceCommandId);
                cSharpProjectContextOleMenuCommand.BeforeQueryStatus += CSharpQueryAndAddMenuItem;
                mcs.AddCommand(cSharpProjectContextOleMenuCommand);

                CommandID fSharpProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidFSharpAddServiceStackReference);
                var       fSharpProjectContextOleMenuCommand     = new OleMenuCommand(FSharpAddReferenceCallback, fSharpProjContextAddReferenceCommandId);
                fSharpProjectContextOleMenuCommand.BeforeQueryStatus += FSharpQueryAndAddMenuItem;
                mcs.AddCommand(fSharpProjectContextOleMenuCommand);

                CommandID fSharpProjContextUpdateReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidFSharpUpdateServiceStackReference);
                var       fSharpProjectContextUpdateOleMenuCommand  = new OleMenuCommand(FSharpUpdateReferenceCallback, fSharpProjContextUpdateReferenceCommandId);
                fSharpProjectContextUpdateOleMenuCommand.BeforeQueryStatus += FSharpQueryAndAddUpdateMenuItem;
                mcs.AddCommand(fSharpProjectContextUpdateOleMenuCommand);
            }

            solutionEventsListener = new SolutionEventsListener();
            solutionEventsListener.OnAfterOpenSolution += SolutionLoaded;
        }
コード例 #2
0
        public ClientWizard(string clientKind, EnvDTE.Project project, IVsUIShell uiShell, IVsPackageInstaller packageInstaller, IVsPackageInstallerServices packageInstallerServices)
        {
            InitializeComponent();

            _clientKind               = clientKind;
            _dte                      = project.DTE;
            _project                  = project;
            _uiShell                  = uiShell;
            _packageInstaller         = packageInstaller;
            _packageInstallerServices = packageInstallerServices;

            var edmxs = _dte.GetSolutionEdmx(_project).ToList();

            edmx.ItemsSource  = edmxs;
            edmx.SelectedItem = edmxs.FirstOrDefault();

            var services = _dte.GetSolutionSvc(_project).ToList();

            service.ItemsSource  = services;
            service.SelectedItem = services.FirstOrDefault();

            generationOptions.ItemsSource   = new[] { GenerationOptions.GetViewModel(GenerationOptions.Kind.All), GenerationOptions.GetViewModel(GenerationOptions.Kind.WithoutGlobalWithoutFramework), GenerationOptions.GetViewModel(GenerationOptions.Kind.FrameworkOnly), GenerationOptions.GetViewModel(GenerationOptions.Kind.GlobalOnly) };
            generationOptions.SelectedIndex = edmxs.Count == 0 || services.Count == 0 ? 2 : 0;

            if (!GenerationOptions.CanBeRunnedWithNoCopy(_dte))
            {
                copyTemplates.IsChecked = true;
                copyTemplates.IsEnabled = false;
            }
        }
コード例 #3
0
        /// <summary>
        /// Ensures the appropriate version of the specified packages are installed.  If an existing version of the package
        /// already exists the following will happen:
        /// If a semantically compatible version already exists, no change is made to the package.
        /// If an older major version exists, a warning is logged and the package is upgraded.
        /// If an older minor/build version exists, an information message is logged and the package is upgraded.
        /// If a newer major version exists, a warning is logged and no change is made to the package.
        /// </summary>
        public static async Task InstallPackagesAsync(
            Dictionary<string, string> packages,
            string extensionId,
            ConnectedServiceLogger logger,
            Project project,
            IVsPackageInstallerServices packageInstallerServices,
            IVsPackageInstaller packageInstaller)
        {
            Dictionary<string, string> packagesToInstall = new Dictionary<string, string>();

            await NuGetUtilities.InstallPackagesAsync(
                project,
                packages,
                (packageId, packageVersion) =>
                {
                    packagesToInstall.Add(packageId, packageVersion);
                    return Task.FromResult<object>(null);
                },
                logger,
                packageInstallerServices);

            if (packagesToInstall.Any())
            {
                packageInstaller.InstallPackagesFromVSExtensionRepository(extensionId, false, false, project, packagesToInstall);
            }
        }
コード例 #4
0
        /// <summary>
        /// Ensures the appropriate version of the specified packages are installed.  If an existing version of the package
        /// already exists the following will happen:
        /// If a semantically compatible version already exists, no change is made to the package.
        /// If an older major version exists, a warning is logged and the package is upgraded.
        /// If an older minor/build version exists, an information message is logged and the package is upgraded.
        /// If a newer major version exists, a warning is logged and no change is made to the package.
        /// </summary>
        public static async Task InstallPackagesAsync(
            Dictionary <string, string> packages,
            string extensionId,
            ConnectedServiceLogger logger,
            Project project,
            IVsPackageInstallerServices packageInstallerServices,
            IVsPackageInstaller packageInstaller)
        {
            Dictionary <string, string> packagesToInstall = new Dictionary <string, string>();

            await NuGetUtilities.InstallPackagesAsync(
                project,
                packages,
                (packageId, packageVersion) =>
            {
                packagesToInstall.Add(packageId, packageVersion);
                return(Task.FromResult <object>(null));
            },
                logger,
                packageInstallerServices);

            if (packagesToInstall.Any())
            {
                packageInstaller.InstallPackagesFromVSExtensionRepository(extensionId, false, false, project, packagesToInstall);
            }
        }
コード例 #5
0
        private void OnConfigureCompileOnBuildCommandInvoked(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (vs != null && vs.TryGetSelectedProject(out EnvDTE.Project project))
            {
                IComponentModel             componentModel = (IComponentModel)GetGlobalService(typeof(SComponentModel));
                IVsPackageInstallerServices nuget          = componentModel.GetService <IVsPackageInstallerServices>();
                IVsPackageInstaller         installer      = componentModel.GetService <IVsPackageInstaller>();
                EnvDTE.StatusBar            status         = vs.StatusBar;

                if (!nuget.IsPackageInstalled(project, nameof(TSBuild)))
                {
                    try
                    {
                        status.Text = $"{Symbol.Name}: installing {nameof(TSBuild)} package...";
                        status.Animate(true, EnvDTE.vsStatusAnimation.vsStatusAnimationBuild);

                        installer.InstallPackage(null, project, nameof(TSBuild), Symbol.Version, false);
                    }
                    catch { status.Text = $"{Symbol.Name}: failed to install {nameof(TSBuild)}."; }
                    finally { status.Animate(false, EnvDTE.vsStatusAnimation.vsStatusAnimationBuild); }
                }
            }
        }
コード例 #6
0
 public PackageServicesProxy(IVsPackageInstallerServices packageInstallerServices, IVsPackageInstaller packageInstaller, IVsPackageUninstaller packageUninstaller, IVsPackageSourceProvider packageSourceProvider)
 {
     _packageInstallerServices = packageInstallerServices;
     _packageInstaller         = packageInstaller;
     _packageUninstaller       = packageUninstaller;
     _packageSourceProvider    = packageSourceProvider;
 }
コード例 #7
0
        private void PostHandleCrmAssemblyProjects(Project project, IVsPackageInstaller installer)
        {
            try
            {
                project.DTE.SuppressUI = true;

                //Install all the NuGet packages
                project = (Project)((Array)_dte.ActiveSolutionProjects).GetValue(0);
                NuGetProcessor.InstallPackage(installer, project, Resource.SdkAssemblyCore, _coreVersion);
                if (_needsWorkflow)
                {
                    NuGetProcessor.InstallPackage(installer, project, Resource.SdkAssemblyWorkflow, _coreVersion);
                }
                if (_needsClient)
                {
                    NuGetProcessor.InstallPackage(installer, project, _clientPackage, _clientVersion);
                }

                ProjectWorker.ExcludeFolder(project, "bin");
                ProjectWorker.ExcludeFolder(project, "performance");

                if (_signAssembly)
                {
                    Signing.GenerateKey(project, _destDirectory);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorProcessingTemplate, ex);
                MessageBox.Show(Resource.ErrorMessage_ErrorProcessingTemplate);
            }
        }
コード例 #8
0
        void SatifyDependencies()
        {
            if (solutionExplorer == null)
            {
                solutionExplorer = ServiceLocator.Global.GetExport <ISolutionExplorer>();
            }

            if (platformProvider == null)
            {
                platformProvider = ServiceLocator.Global.GetExport <IPlatformProvider>();
            }

            if (uiShell == null)
            {
                uiShell = ServiceLocator.Global.GetService <SVsUIShell, IVsUIShell>();
            }

            if (packageInstaller == null)
            {
                packageInstaller = ServiceLocator.Global.GetExport <IVsPackageInstaller>();
            }

            if (packageInstallerServices == null)
            {
                packageInstallerServices = ServiceLocator.Global.GetExport <IVsPackageInstallerServices>();
            }
        }
コード例 #9
0
ファイル: CheckRequiredReferences.cs プロジェクト: vebin/Eto
        private void InstallReferences(IVsPackageInstaller installerServices, List <MissingReference> missingReferences)
        {
            if (missingReferences.Count > 0)
            {
                var packages = string.Join(", ", missingReferences.Select(r => r.Reference.Package));
                var msg      = string.Format("This template requires these references. Do you want to add them using nuget?\n\n{0}", packages);

                if (!Quiet)
                {
                    var result = MessageBox.Show(Helpers.MainWindow, msg, "Missing packages", MessageBoxButtons.OKCancel, MessageBoxType.Information, MessageBoxDefaultButton.OK);
                    if (result == DialogResult.Cancel)
                    {
                        throw new WizardCancelledException();
                    }
                }

                foreach (var missingRef in missingReferences)
                {
                    SetStatusMessage(string.Format("Adding {0}.{1} to project...", missingRef.Reference.Package, missingRef.Reference.Version));
                    var reference = missingRef.Reference;
                    if (!string.IsNullOrEmpty(reference.ExtensionId))
                    {
                        installerServices.InstallPackagesFromVSExtensionRepository(reference.ExtensionId, false, false, false, missingRef.Project, new Dictionary <string, string>
                        {
                            { reference.Package, reference.Version }
                        });
                    }
                    else
                    {
                        installerServices.InstallPackage("https://packages.nuget.org", missingRef.Project, reference.Package, reference.Version, false);
                    }
                }
            }
        }
コード例 #10
0
        private ILookup<string, FileSystemPath> installedPackages; // there can be several versions of one package (different versions)

        #endregion Fields

        #region Constructors

        public NuGetApi(ISolution solution, Lifetime lifetime, IComponentModel componentModel, IThreading threading, ProjectModelSynchronizer projectModelSynchronizer)
        {
            this.solution = solution;
            this.threading = threading;
            this.projectModelSynchronizer = projectModelSynchronizer;
            try
            {
                vsPackageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().SingleOrDefault();
                vsPackageInstaller = componentModel.GetExtensions<IVsPackageInstaller>().SingleOrDefault();
                vsPackageInstallerEvents = componentModel.GetExtensions<IVsPackageInstallerEvents>().SingleOrDefault();
            }
            catch (Exception e)
            {
                Logger.LogException("Unable to get NuGet interfaces.", e);
            }

            if (!IsNuGetAvailable)
            {
                Logger.LogMessage(LoggingLevel.VERBOSE, "[NUGET PLUGIN] Unable to get NuGet interfaces. No exception thrown");
                return;
            }

            lifetime.AddBracket(
              () => vsPackageInstallerEvents.PackageInstalled += RecalcInstalledPackages,
              () => vsPackageInstallerEvents.PackageInstalled -= RecalcInstalledPackages);

              lifetime.AddBracket(
              () => vsPackageInstallerEvents.PackageUninstalled += RecalcInstalledPackages,
              () => vsPackageInstallerEvents.PackageUninstalled -= RecalcInstalledPackages);

              RecalcInstalledPackages(null);
        }
コード例 #11
0
ファイル: CheckRequiredReferences.cs プロジェクト: mhusen/Eto
		private void InstallReferences(IVsPackageInstaller installerServices, List<MissingReference> missingReferences)
		{
			if (missingReferences.Count > 0)
			{
				var packages = string.Join(", ", missingReferences.Select(r => r.Reference.Package));
				var msg = string.Format("This template requires these references. Do you want to add them using nuget?\n\n{0}", packages);

				if (!Quiet)
				{
					var result = MessageBox.Show(Helpers.MainWindow, msg, "Missing packages", MessageBoxButtons.OKCancel, MessageBoxType.Information, MessageBoxDefaultButton.OK);
					if (result == DialogResult.Cancel)
						throw new WizardCancelledException();
				}

				foreach (var missingRef in missingReferences)
				{
					SetStatusMessage(string.Format("Adding {0}.{1} to project...", missingRef.Reference.Package, missingRef.Reference.Version));
					var reference = missingRef.Reference;
					if (!string.IsNullOrEmpty(reference.ExtensionId))
					{
						installerServices.InstallPackagesFromVSExtensionRepository(reference.ExtensionId, false, false, false, missingRef.Project, new Dictionary<string, string>
							{
								{ reference.Package, reference.Version }
							});
					}
					else
					{
						installerServices.InstallPackage("https://packages.nuget.org", missingRef.Project, reference.Package, reference.Version, false);
					}
				}
			}
		}
コード例 #12
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var question = MessageBox.Show("Selecting this command will install a NuGet package that will enable this project for script generation. " +
                                           "\r\rDo you want to continue?", "Install NuGet Package?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (question == DialogResult.No)
            {
                return;
            }

            foreach (Project proj in VsHelper.GetSelectedCsharpProjects())
            {
                if (!VsHelper.IsPackageInstalled(proj))
                {
                    try
                    {
                        IComponentModel     componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
                        IVsPackageInstaller installer      = componentModel.GetService <IVsPackageInstaller>();
                        installer.InstallPackage(null, proj, TypeRightPackage.NugetID, (string)null, false);
                    }
                    catch (Exception exception)
                    {
                        // Show a message box to prove we were here
                        VsShellUtilities.ShowMessageBox(
                            this.ServiceProvider,
                            "There was an error installing the package: \n\n" + exception.Message,
                            "Could not install package",
                            OLEMSGICON.OLEMSGICON_CRITICAL,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                    }
                }
            }
        }
コード例 #13
0
        private void OnInstallNugetPackageCommandInvoked(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (vs != null && vs.TryGetSelectedProject(out EnvDTE.Project project))
            {
                IComponentModel             componentModel = (IComponentModel)GetGlobalService(typeof(SComponentModel));
                IVsPackageInstallerServices nuget          = componentModel.GetService <IVsPackageInstallerServices>();
                IVsPackageInstaller         installer      = componentModel.GetService <IVsPackageInstaller>();
                EnvDTE.StatusBar            status         = vs.StatusBar;

                if (!nuget.IsPackageInstalled(project, nameof(Sassin)))
                {
                    try
                    {
                        status.Text = $"{Metadata.ProductName} installing {nameof(Sassin)}...";
                        status.Animate(true, EnvDTE.vsStatusAnimation.vsStatusAnimationBuild);

                        installer.InstallPackage(null, project, nameof(Sassin), Convert.ToString(null), false);
                    }
                    catch { status.Text = $"{Metadata.ProductName} failed to install {nameof(Sassin)}."; }
                    finally { status.Animate(false, EnvDTE.vsStatusAnimation.vsStatusAnimationBuild); }
                }
            }
        }
コード例 #14
0
ファイル: VsTemplateWizard.cs プロジェクト: TMFRook/NuGet
 public VsTemplateWizard(IVsPackageInstaller installer, IVsWebsiteHandler websiteHandler, IVsPackageInstallerServices packageServices, IOutputConsoleProvider consoleProvider)
 {
     _installer       = installer;
     _websiteHandler  = websiteHandler;
     _packageServices = packageServices;
     _consoleProvider = consoleProvider;
 }
コード例 #15
0
        private static void InstallPackageDependency(
            Project project,
            PackageDependency packageDependency,
            IReadOnlyCollection <IVsPackageMetadata> installedPackages,
            IVsPackageInstaller packageInstaller)
        {
            var packageId = packageDependency.Name;
            var version   = packageDependency.Version;

            if (installedPackages.Any(c => string.Equals(c.Id, packageId, StringComparison.InvariantCultureIgnoreCase)) &&
                (installedPackages.Any(c => c.VersionString == version.ToString(3)) || !packageDependency.ForceUpdate))
            {
                Trace.WriteLine($"{packageDependency.Name} is already installed");
                return;
            }

            Trace.WriteLine($"Installing {packageId} version {version}");

            try
            {
                packageInstaller.InstallPackage(
                    null,
                    project,
                    packageId,
                    version,
                    true);

                Trace.WriteLine($"Successfully installed {packageId} version {version}");
            }
            catch (Exception e)
            {
                Trace.WriteLine($"Unable to install {packageId} version {version}");
                Trace.WriteLine(e);
            }
        }
コード例 #16
0
ファイル: VsTemplateWizard.cs プロジェクト: xero-github/Nuget
 public VsTemplateWizard(IVsPackageInstaller installer, IVsWebsiteHandler websiteHandler, IVsPackageInstallerServices packageServices, IOutputConsoleProvider consoleProvider)
 {
     _installer = installer;
     _websiteHandler = websiteHandler;
     _packageServices = packageServices;
     _consoleProvider = consoleProvider;
 }
コード例 #17
0
 protected override void InstallNugetDependencies(Project proj, IVsPackageInstaller installer, IVsPackageMetadata[] packs)
 {
     NugetInstallerHelper.InstallPackageIfNeeded(proj, packs, installer, NewtonsoftJsonPackageId, "9.0.1", Settings.Default.NugetExternalPackagesSource);
     NugetInstallerHelper.InstallPackageIfNeeded(proj, packs, installer, "Microsoft.AspNet.WebApi.Client", "5.2.3", Settings.Default.NugetExternalPackagesSource);
     NugetInstallerHelper.InstallPackageIfNeeded(proj, packs, installer, "System.Xml.XmlSerializer", "4.3.0", Settings.Default.NugetExternalPackagesSource);
     NugetInstallerHelper.InstallPackageIfNeeded(proj, packs, installer, "System.Runtime.Serialization.Xml", "4.3.0", Settings.Default.NugetExternalPackagesSource);
 }
コード例 #18
0
ファイル: TestLocator.cs プロジェクト: yannduran/TddHelper
 public TestLocator(DTE2 dte, IVsUIShell shell, IVsPackageInstaller packageInstaller, IProjectModel project)
 {
     Access.Dte              = dte;
     Access.Shell            = shell;
     Access.ProjectModel     = project;
     Access.PackageInstaller = packageInstaller;
 }
コード例 #19
0
        public VsTemplateWizard(
            IVsPackageInstaller installer,
#pragma warning disable CS0618 // Type or member is obsolete
            IVsPackageInstallerServices packageServices,
#pragma warning restore CS0618 // Type or member is obsolete
            IOutputConsoleProvider consoleProvider,
            IVsSolutionManager solutionManager,
            Configuration.ISettings settings,
            ISourceRepositoryProvider sourceProvider,
            IVsProjectAdapterProvider vsProjectAdapterProvider
            )
        {
            _installer                    = installer;
            _packageServices              = packageServices;
            _consoleProvider              = consoleProvider;
            _solutionManager              = solutionManager;
            _settings                     = settings;
            _sourceProvider               = sourceProvider;
            _vsProjectAdapterProvider     = vsProjectAdapterProvider;
            _preinstalledPackageInstaller = new Lazy <PreinstalledPackageInstaller>(() =>
            {
                return(new PreinstalledPackageInstaller(_packageServices, _solutionManager, _settings, _sourceProvider, (VsPackageInstaller)_installer, _vsProjectAdapterProvider));
            });
            PumpingJTF = new PumpingJTF(NuGetUIThreadHelper.JoinableTaskFactory);
        }
コード例 #20
0
 private static void InstallNugetPackageForSpecifiedVersion(IProject project, IVsPackageInstaller vsPackageInstaller, string packageName, string version)
 {
     vsPackageInstaller.InstallPackage("All",
                                       project.As <EnvDTE.Project>(),
                                       packageName,
                                       version,
                                       false);
 }
コード例 #21
0
ファイル: IFixtureMixin.cs プロジェクト: a-powolozki/Prig
 static void Realize(IVsPackageInstaller installer)
 {
     installer.InstallPackage(default(string), default(Project), default(string), default(string), default(bool));
     installer.InstallPackage(default(string), default(Project), default(string), default(Version), default(bool));
     installer.InstallPackagesFromRegistryRepository(default(string), default(bool), default(bool), default(Project), default(IDictionary <string, string>));
     installer.InstallPackagesFromRegistryRepository(default(string), default(bool), default(bool), default(bool), default(Project), default(IDictionary <string, string>));
     installer.InstallPackagesFromVSExtensionRepository(default(string), default(bool), default(bool), default(Project), default(IDictionary <string, string>));
     installer.InstallPackagesFromVSExtensionRepository(default(string), default(bool), default(bool), default(bool), default(Project), default(IDictionary <string, string>));
 }
コード例 #22
0
ファイル: NetIdeWizard.cs プロジェクト: netide/netide
 public NetIdeWizard()
 {
     _installer = Support.ServiceLocator.GetInstance<IVsPackageInstaller>();
     if (_installer == null)
         throw new InvalidOperationException("Could not resolve the IVsPackageInstaller service");
     _dte = Support.ServiceLocator.GetInstance<DTE>();
     if (_installer == null)
         throw new InvalidOperationException("Could not resolve the DTE service");
 }
コード例 #23
0
 private static void InstallNugetPackageForSpecifiedVersion(IProject project, IVsPackageInstaller vsPackageInstaller, string packageId, string version)
 {
     vsPackageInstaller.InstallPackage(
         ServiceMatrixOverrides.GetNugetFeedServiceBaseAddress() ?? "All",
         project.As <EnvDTE.Project>(),
         packageId,
         version,
         false);
 }
コード例 #24
0
 public PackageHandler(EnvDTE.Project project, IVsPackageInstallerServices packageServices, IVsPackageInstaller installer,
                       IVsPackageUninstaller uninstaller, IVsPackageInstallerEvents events)
     : this(project, packageServices, installer, uninstaller, events, null)
 {
     m_project         = project;
     m_packageServices = packageServices;
     m_installer       = installer;
     m_uninstaller     = uninstaller;
     m_events          = events;
 }
コード例 #25
0
        private void PostHandleUnitTestProjects(Project project, IVsPackageInstaller installer)
        {
            NuGetProcessor.InstallPackage(_dte, installer, project, "MSTest.TestAdapter", "1.1.18");
            NuGetProcessor.InstallPackage(_dte, installer, project, "MSTest.TestFramework", "1.1.18");

            if (_unitTestFrameworkPackage != null)
            {
                NuGetProcessor.InstallPackage(_dte, installer, project, _unitTestFrameworkPackage, null);
            }
        }
コード例 #26
0
        private void PostHandleUnitTestProjects(Project project, IVsPackageInstaller installer)
        {
            NuGetProcessor.InstallPackage(installer, project, ExtensionConstants.MsTestTestAdapter, null);
            NuGetProcessor.InstallPackage(installer, project, ExtensionConstants.MsTestTestFramework, null);

            if (_unitTestFrameworkPackage != null)
            {
                NuGetProcessor.InstallPackage(installer, project, _unitTestFrameworkPackage, null);
            }
        }
コード例 #27
0
        private void InstallBadSourceTest(object sender, EventArgs e)
        {
            EnvDTE.DTE          dte      = ServiceLocator.GetInstance <EnvDTE.DTE>();
            IVsPackageInstaller services = ServiceLocator.GetInstance <IVsPackageInstaller>();

            foreach (EnvDTE.Project project in dte.Solution.Projects)
            {
                _task = System.Threading.Tasks.Task.Run(() => services.InstallPackage("http://packagesource", project, "newtonsoft.json", "6.0.4", false));
                return;
            }
        }
コード例 #28
0
        public static void InstallPackageApiBadSource(string id, string version)
        {
            EnvDTE.DTE          dte      = ServiceLocator.GetInstance <EnvDTE.DTE>();
            IVsPackageInstaller services = ServiceLocator.GetInstance <IVsPackageInstaller>();

            foreach (EnvDTE.Project project in dte.Solution.Projects)
            {
                services.InstallPackage("http://packagesource", project, id, version, false);
                return;
            }
        }
コード例 #29
0
        private void InstallPackageEmptyVersionTest(object sender, EventArgs e)
        {
            EnvDTE.DTE          dte      = ServiceLocator.GetInstance <EnvDTE.DTE>();
            IVsPackageInstaller services = ServiceLocator.GetInstance <IVsPackageInstaller>();

            foreach (EnvDTE.Project project in dte.Solution.Projects)
            {
                _task = System.Threading.Tasks.Task.Run(() => services.InstallPackage("https://api.nuget.org/v2/", project, "newtonsoft.json", "", false));
                return;
            }
        }
コード例 #30
0
        public static void InstallPackageApi(string source, string id, string version, bool prerelease)
        {
            var dte = ServiceLocator.GetInstance <EnvDTE.DTE>();
            IVsPackageInstaller services = ServiceLocator.GetInstance <IVsPackageInstaller>();

            foreach (EnvDTE.Project project in dte.Solution.Projects)
            {
                services.InstallPackage(source, project, id, version, prerelease);
                return;
            }
        }
コード例 #31
0
 /// <summary>
 /// Installs the specified NuGet package and displays a message in the status bar.
 /// </summary>
 /// <param name="installer">The VS package installer.</param>
 /// <param name="project">The target project.</param>
 /// <param name="package">The NuGet package name.</param>
 /// <param name="version">The NuGet package version.</param>
 private void InstallPackage(IVsPackageInstaller installer, Project project, string package, string version)
 {
     _dte.StatusBar.Text = @"Installing " + package + "...";
     if (!string.IsNullOrEmpty(version))
     {
         installer.InstallPackage("http://packages.nuget.org", project, package, version, false);
     }
     else
     {
         installer.InstallPackage("http://packages.nuget.org", project, package, (Version)null, false);
     }
 }
コード例 #32
0
ファイル: CheckRequiredReferences.cs プロジェクト: vebin/Eto
        IEnumerable <MissingReference> FindMissingReferences(IVsPackageInstaller installerServices, EnvDTE.DTE dte)
        {
            var activeProjects = ((Array)dte.ActiveSolutionProjects).OfType <EnvDTE.Project>().ToList();

            foreach (var proj in activeProjects)
            {
                foreach (var item in FindMissingReferences(proj))
                {
                    yield return(item);
                }
            }
        }
コード例 #33
0
 public NuGetApi(IComponentModel componentModel, IThreading threading)
 {
     this.threading = threading;
     try
     {
         vsPackageInstallerServices = componentModel.GetExtensions <IVsPackageInstallerServices>().SingleOrDefault();
         vsPackageInstaller         = componentModel.GetExtensions <IVsPackageInstaller>().SingleOrDefault();
     }
     catch (Exception e)
     {
         Logger.LogException("Unable to get NuGet interfaces.", e);
     }
 }
コード例 #34
0
ファイル: NetIdeWizard.cs プロジェクト: vector-man/netide
 public NetIdeWizard()
 {
     _installer = Support.ServiceLocator.GetInstance <IVsPackageInstaller>();
     if (_installer == null)
     {
         throw new InvalidOperationException("Could not resolve the IVsPackageInstaller service");
     }
     _dte = Support.ServiceLocator.GetInstance <DTE>();
     if (_installer == null)
     {
         throw new InvalidOperationException("Could not resolve the DTE service");
     }
 }
コード例 #35
0
 public PackageManagerConverter(
     IConverterViewProvider converterViewProvider,
     IVsPackageInstaller installer,
     IVsPackageUninstaller uninstaller,
     IVsPackageRestorer restorer,
     IVsFrameworkParser frameworkParser)
 {
     _converterViewProvider = converterViewProvider;
     _installer             = installer;
     _uninstaller           = uninstaller;
     _restorer        = restorer;
     _frameworkParser = frameworkParser;
 }
コード例 #36
0
        public static void InstallPackageIfNeeded(Project proj, IEnumerable<IVsPackageMetadata> packs, IVsPackageInstaller installer, 
            string packageId, string packageVersion, string nugetPackagesSource = null)
        {
            var packageMetadata = packs.FirstOrDefault(p => p.Id == packageId);
            if (packageMetadata == null ||
                !IsSameOrNewerVersion(packageMetadata.VersionString, packageVersion))
            {
                if (nugetPackagesSource == null)
                    nugetPackagesSource = Settings.Default.NugetPackagesSource;

                installer.InstallPackage(nugetPackagesSource, proj, packageId, packageVersion, false);
            }
        }
コード例 #37
0
 public VsTemplateWizard(
     IVsPackageInstaller installer,
     IVsWebsiteHandler websiteHandler,
     IVsPackageInstallerServices packageServices,
     IOutputConsoleProvider consoleProvider,
     IVsCommonOperations vsCommonOperations,
     ISolutionManager solutionManager)
 {
     _installer = installer;
     _websiteHandler = websiteHandler;
     _packageServices = packageServices;
     _consoleProvider = consoleProvider;
     _vsCommonOperations = vsCommonOperations;
     _solutionManager = solutionManager;
 }
コード例 #38
0
        public VsTemplateWizard(
            IVsPackageInstaller installer,
            IVsPackageInstallerServices packageServices,
            IOutputConsoleProvider consoleProvider,
            ISolutionManager solutionManager,
            ISettings settings,
            ISourceRepositoryProvider sourceProvider
            )
        {
            _installer = installer;
            _packageServices = packageServices;
            _consoleProvider = consoleProvider;
            _solutionManager = solutionManager;
            _settings = settings;
            _sourceProvider = sourceProvider;

            _preinstalledPackageInstaller = new PreinstalledPackageInstaller(_packageServices, _solutionManager, _settings, _sourceProvider, (VsPackageInstaller)_installer);
        }
コード例 #39
0
ファイル: ServerWizard.xaml.cs プロジェクト: bnjMichel/waqs
        public ServerWizard(EnvDTE.Project project, IVsUIShell uiShell, IVsPackageInstaller packageInstaller, IVsPackageInstallerServices packageInstallerServices)
        {
            InitializeComponent();

            _dte = project.DTE;
            _project = project;
            _uiShell = uiShell;
            _packageInstaller = packageInstaller;
            _packageInstallerServices = packageInstallerServices;

            var edmxs = _dte.GetSolutionEdmx(_project).ToList();
            edmx.ItemsSource = edmxs;
            edmx.SelectedItem = edmxs.FirstOrDefault();

            generationOptions.ItemsSource = new[] { GenerationOptions.GetViewModel(GenerationOptions.Kind.All), GenerationOptions.GetViewModel(GenerationOptions.Kind.WithoutGlobalWithoutFramework), GenerationOptions.GetViewModel(GenerationOptions.Kind.FrameworkOnly), GenerationOptions.GetViewModel(GenerationOptions.Kind.GlobalOnly) };
            generationOptions.SelectedIndex = edmxs.Count == 0 ? 2 : 0;

            if (! GenerationOptions.CanBeRunnedWithNoCopy(_dte))
            {
                copyTemplates.IsChecked = true;
                copyTemplates.IsEnabled = false;
            }
        }
コード例 #40
0
ファイル: CheckRequiredReferences.cs プロジェクト: picoe/Eto
		private void InstallReferences(IVsPackageInstaller installerServices, List<MissingReference> missingReferences)
		{
			if (missingReferences.Count > 0)
			{
				var packages = string.Join(", ", missingReferences.Select(r => r.Reference.Package));
				var msg = string.Format("This template requires these references. Do you want to add them using nuget?\n\n{0}", packages);

				if (!Quiet)
				{
					var result = MessageBox.Show(Helpers.MainWindow, msg, "Missing packages", MessageBoxButtons.YesNoCancel, MessageBoxType.Information, MessageBoxDefaultButton.Yes);
					if (result == DialogResult.Cancel)
						throw new WizardCancelledException();
					if (result == DialogResult.No)
						return;
				}

				foreach (var missingRef in missingReferences)
				{
					SetStatusMessage(string.Format("Adding {0}.{1} to project...", missingRef.Reference.Package, missingRef.Reference.Version));
					var reference = missingRef.Reference;
					if (!string.IsNullOrEmpty(reference.ExtensionId))
					{
						installerServices.InstallPackagesFromVSExtensionRepository(reference.ExtensionId, false, false, false, missingRef.Project, new Dictionary<string, string>
							{
								{ reference.Package, reference.Version }
							});
					}
					else
					{
						// "All" specifies to use configured package sources.
						// http://blog.nuget.org/20120926/invoking-nuget-services-from-inside-visual-studio.html#comment-686825894
						installerServices.InstallPackage("All", missingRef.Project, reference.Package, reference.Version, false);
					}
				}
			}
		}
コード例 #41
0
        /// <summary>
        /// Installs one or more packages into the specified project.
        /// </summary>
        /// <param name="packageInstaller">The package installer service that performs the actual package installation.</param>
        /// <param name="project">The target project for installation.</param>
        /// <param name="configuration">The packages to install, where to install them from, and additional options for their installation.</param>
        /// <param name="repositorySettings">The repository settings for the packages being installed.</param>
        /// <param name="warningHandler">An action that accepts a warning message and presents it to the user, allowing execution to continue.</param>
        /// <param name="errorHandler">An action that accepts an error message and presents it to the user, allowing execution to continue.</param>
        internal void PerformPackageInstall(
            IVsPackageInstaller packageInstaller,
            Project project,
            PreinstalledPackageConfiguration configuration,
            Lazy<IRepositorySettings> repositorySettings,
            Action<string> warningHandler,
            Action<string> errorHandler)
        {
            string repositoryPath = configuration.RepositoryPath;
            var failedPackageErrors = new List<string>();

            IPackageRepository repository = configuration.IsPreunzipped
                                                ? (IPackageRepository)new UnzippedPackageRepository(repositoryPath)
                                                : (IPackageRepository)new LocalPackageRepository(repositoryPath);

            foreach (var package in configuration.Packages)
            {
                // Does the project already have this package installed?
                if (_packageServices.IsPackageInstalled(project, package.Id))
                {
                    // If so, is it the right version?
                    if (!_packageServices.IsPackageInstalled(project, package.Id, package.Version))
                    {
                        // No? Raise a warning (likely written to the Output window) and ignore this package.
                        warningHandler(String.Format(VsResources.PreinstalledPackages_VersionConflict, package.Id, package.Version));
                    }
                    // Yes? Just silently ignore this package!
                }
                else
                {
                    try
                    {
                        if (InfoHandler != null)
                        {
                            InfoHandler(String.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_PackageInstallStatus, package.Id, package.Version));
                        }

                        packageInstaller.InstallPackage(repository, project, package.Id, package.Version.ToString(), ignoreDependencies: true, skipAssemblyReferences: package.SkipAssemblyReferences);
                    }
                    catch (InvalidOperationException exception)
                    {
                        failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message);
                    }
                }
            }

            if (failedPackageErrors.Any())
            {
                var errorString = new StringBuilder();
                errorString.AppendFormat(VsResources.PreinstalledPackages_FailedToInstallPackage, repositoryPath);
                errorString.AppendLine();
                errorString.AppendLine();
                errorString.Append(String.Join(Environment.NewLine, failedPackageErrors));

                errorHandler(errorString.ToString());
            }

            // RepositorySettings = null in unit tests
            if (project.IsWebSite() && repositorySettings != null)
            {
                using (_vsCommonOperations.SaveSolutionExplorerNodeStates(_solutionManager))
                {
                    CreateRefreshFilesInBin(
                        project,
                        repositorySettings.Value.RepositoryPath,
                        configuration.Packages.Where(p => p.SkipAssemblyReferences));

                    CopyNativeBinariesToBin(project, repositorySettings.Value.RepositoryPath, configuration.Packages);
                }
            }
        }
コード例 #42
0
ファイル: CheckRequiredReferences.cs プロジェクト: picoe/Eto
		IEnumerable<MissingReference> FindMissingReferences(IVsPackageInstaller installerServices, EnvDTE.DTE dte)
		{
			var activeProjects = ((Array)dte.ActiveSolutionProjects).OfType<EnvDTE.Project>().ToList();
			foreach (var proj in activeProjects)
			{
				foreach (var item in FindMissingReferences(proj))
					yield return item;
			}
		}
コード例 #43
0
 /// <summary>
 /// Installs the specified NuGet package and displays a message in the status bar.
 /// </summary>
 /// <param name="installer">The VS package installer.</param>
 /// <param name="project">The target project.</param>
 /// <param name="package">The NuGet package name.</param>
 /// <param name="version">The NuGet package version.</param>
 private void InstallPackage(IVsPackageInstaller installer, Project project, string package, string version)
 {
     try
     {
         _dte.StatusBar.Text = @"Installing " + package + "...";
         if (!string.IsNullOrEmpty(version))
             installer.InstallPackage("http://packages.nuget.org", project, package, version, false);
         else
             installer.InstallPackage("http://packages.nuget.org", project, package, (Version)null, false);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error Processing Template: Error Installing NuGet Package: " + ex.Message);
     }
 }
コード例 #44
0
        private void StartWorker()
        {
            var componentModel = _workspace.GetVsService<SComponentModel, IComponentModel>();
            _packageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().FirstOrDefault();
            _packageInstaller = componentModel.GetExtensions<IVsPackageInstaller>().FirstOrDefault();
            _packageUninstaller = componentModel.GetExtensions<IVsPackageUninstaller>().FirstOrDefault();
            _packageSourceProvider = componentModel.GetExtensions<IVsPackageSourceProvider>().FirstOrDefault();

            if (!this.IsEnabled)
            {
                return;
            }

            // Start listening to workspace changes.
            _workspace.WorkspaceChanged += OnWorkspaceChanged;
            _packageSourceProvider.SourcesChanged += OnSourceProviderSourcesChanged;

            OnSourceProviderSourcesChanged(null, EventArgs.Empty);
        }
コード例 #45
0
        public static void InstallNuGetPackage(this IProject project, IVsPackageInstallerServices vsPackageInstallerServices, IVsPackageInstaller vsPackageInstaller, IStatusBar StatusBar, string packageName, string targetNsbVersion)
        {
            string packageId;
            int? majorVersion;

            GetPackageIdAndMajorVersion(packageName, targetNsbVersion, out packageId, out majorVersion);

            try
            {
                var version = NugetPackageVersionManager.GetVersionFromCacheForPackage(packageId, majorVersion);

                if (!String.IsNullOrEmpty(version))
                {
                    StatusBar.DisplayMessage(String.Format("Installing Package: {0} {1}...", packageId, version));
                    try
                    {
                        InstallNugetPackageForSpecifiedVersion(project, vsPackageInstaller, packageId, version);
                    }
                    catch (Exception installException)
                    {
                        StatusBar.DisplayMessage(String.Format("When attempting to install version {0} of the package {1}, the following error occured: {2}.. Going to now try installing the latest version of Package ...", version, packageId, installException.Message));
                        // There was a problem installing the specified version of the package. Try the installing the latest available package from the source.
                        InstallLatestNugetPackage(project, vsPackageInstallerServices, vsPackageInstaller, packageId, majorVersion);
                    }
                }
                else
                {
                    StatusBar.DisplayMessage(String.Format("Installing the latest version of Package: {0}...", packageId));
                    InstallLatestNugetPackage(project, vsPackageInstallerServices, vsPackageInstaller, packageId, majorVersion);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("NuGet Package {0} cannot be installed ({1}).", packageId, ex.Message), ex);
            }
            finally
            {
                StatusBar.DisplayMessage("");
            }
        }
コード例 #46
0
        private static void InstallLatestNugetPackage(IProject project,IVsPackageInstallerServices vsPackageInstallerServices, IVsPackageInstaller vsPackageInstaller, string packageName)
        {
            vsPackageInstaller.InstallPackage("All",
                 project.As<EnvDTE.Project>(),
                 packageName,
                 (Version)null,
                 false);

            // Call the installed packages to get the version that was just installed and cache the version.
            var installedPackages = vsPackageInstallerServices.GetInstalledPackages();
            NugetPackageVersionManager.UpdateCache(packageName, installedPackages);
        }
コード例 #47
0
 private static void InstallNugetPackageForSpecifiedVersion(IProject project, IVsPackageInstaller vsPackageInstaller, string packageName, string version)
 {
     vsPackageInstaller.InstallPackage("All",
          project.As<EnvDTE.Project>(),
          packageName,
          version,
          false);
 }
コード例 #48
0
 private static void InstallNugetPackageForSpecifiedVersion(IProject project, IVsPackageInstaller vsPackageInstaller, string packageId, string version)
 {
     vsPackageInstaller.InstallPackage(
         ServiceMatrixOverrides.GetNugetFeedServiceBaseAddress() ?? "All",
         project.As<EnvDTE.Project>(),
         packageId,
         version,
         false);
 }
コード例 #49
0
        private static void InstallLatestNugetPackage(IProject project, IVsPackageInstallerServices vsPackageInstallerServices, IVsPackageInstaller vsPackageInstaller, string packageId, int? majorVersion)
        {
            // lookup latest version for the given major (or null), and install that
            var latestVersion = GetLatestVersionForMajor(packageId, majorVersion);

            vsPackageInstaller.InstallPackage(
                ServiceMatrixOverrides.GetNugetFeedServiceBaseAddress() ?? "All",
                project.As<EnvDTE.Project>(),
                packageId,
                latestVersion,
                false);

            // Call the installed packages to get the version that was just installed and cache the version.
            // Packages are needed in case latestVersion is null,
            var installedPackages = vsPackageInstallerServices.GetInstalledPackages();
            NugetPackageVersionManager.UpdateCache(packageId, majorVersion, installedPackages);
        }
コード例 #50
0
 public static void InstallNugetPackageForSpecifiedVersion(this IProject project, IVsPackageInstallerServices vsPackageInstallerServices, IVsPackageInstaller vsPackageInstaller, IStatusBar StatusBar, string packageName, string version)
 {
     try
     {
         StatusBar.DisplayMessage(String.Format("Installing Package: {0} {1}...", packageName, version));
         try
         {
             InstallNugetPackageForSpecifiedVersion(project, vsPackageInstaller, packageName, version);
         }
         catch (Exception installException)
         {
             StatusBar.DisplayMessage(String.Format("When attempting to install version {0} of the package {1}, the following error occured: {2}.. Going to now try installing the latest version of Package ...", version, packageName, installException.Message));
         }
     }
     catch (Exception ex)
     {
         throw new Exception(String.Format("NuGet Package {0} cannot be installed ({1}).", packageName, ex.Message), ex);
     }
     finally
     {
         StatusBar.DisplayMessage("");
     }
 }
コード例 #51
0
        private void PerformPackageInstall(
            IVsPackageInstaller packageInstaller,
            Project project,
            VsTemplateWizardInstallerConfiguration configuration)
        {
            string repositoryPath = configuration.RepositoryPath;
            var failedPackageErrors = new List<string>();

            IPackageRepository repository = configuration.IsPreunzipped
                                                ? (IPackageRepository)new UnzippedPackageRepository(repositoryPath)
                                                : (IPackageRepository)new LocalPackageRepository(repositoryPath);

            foreach (var package in configuration.Packages)
            {
                // Does the project already have this package installed?
                if (_packageServices.IsPackageInstalled(project, package.Id))
                {
                    // If so, is it the right version?
                    if (!_packageServices.IsPackageInstalled(project, package.Id, package.Version))
                    {
                        // No? OK, write a message to the Output window and ignore this package.
                        ShowWarningMessage(String.Format(VsResources.TemplateWizard_VersionConflict, package.Id, package.Version));
                    }
                    // Yes? Just silently ignore this package!
                }
                else
                {
                    try
                    {
                        _dte.StatusBar.Text = String.Format(CultureInfo.CurrentCulture, VsResources.TemplateWizard_PackageInstallStatus, package.Id, package.Version);
                        packageInstaller.InstallPackage(repository, project, package.Id, package.Version.ToString(), ignoreDependencies: true, skipAssemblyReferences: package.SkipAssemblyReferences);
                    }
                    catch (InvalidOperationException exception)
                    {
                        failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message);
                    }
                }
            }

            if (failedPackageErrors.Any())
            {
                var errorString = new StringBuilder();
                errorString.AppendFormat(VsResources.TemplateWizard_FailedToInstallPackage, repositoryPath);
                errorString.AppendLine();
                errorString.AppendLine();
                errorString.Append(String.Join(Environment.NewLine, failedPackageErrors));
                ShowErrorMessage(errorString.ToString());
            }
        }
コード例 #52
0
        private void HandleTypeScriptProject(Project project, IVsPackageInstaller installer)
        {
            try
            {
                InstallPackage(installer, project, "xrm.TypeScript.DefinitelyTyped", null);

                //Remove the files that don't match the selected version
                ProjectItem scripts = project.ProjectItems.Item("Scripts");
                ProjectItem typings = scripts.ProjectItems.Item("typings");
                ProjectItem xrm = typings.ProjectItems.Item("xrm");

                ProjectItem xrm6 = xrm.ProjectItems.Item("xrm-6.d.ts");
                ProjectItem xrm70 = xrm.ProjectItems.Item("xrm-7.0.d.ts");
                ProjectItem xrm71 = xrm.ProjectItems.Item("xrm.d.ts");
                ProjectItem para = xrm.ProjectItems.Item("parature.d.ts");
                string filename;

                switch (_sdkVersion)
                {
                    case "CRM 2013 (6.0.X)":
                        filename = xrm70.FileNames[0];
                        xrm70.Remove();
                        File.Delete(filename);

                        filename = xrm71.FileNames[0];
                        xrm71.Remove();
                        File.Delete(filename);

                        filename = para.FileNames[0];
                        para.Remove();
                        File.Delete(filename);
                        break;
                    case "CRM 2015 (7.0.X)":
                        filename = xrm6.FileNames[0];
                        xrm6.Remove();
                        File.Delete(filename);

                        filename = xrm71.FileNames[0];
                        xrm71.Remove();
                        File.Delete(filename);

                        filename = para.FileNames[0];
                        para.Remove();
                        File.Delete(filename);
                        break;
                    case "CRM 2015 (7.1.X)":
                        filename = xrm6.FileNames[0];
                        xrm6.Remove();
                        File.Delete(filename);

                        filename = xrm70.FileNames[0];
                        xrm70.Remove();
                        File.Delete(filename);
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Processing Template: " + ex.Message);
            }
        }
コード例 #53
0
 /// <summary>
 /// Installs the specified NuGet package and displays a message in the status bar.
 /// </summary>
 /// <param name="installer">The VS package installer.</param>
 /// <param name="project">The target project.</param>
 /// <param name="package">The NuGet package name.</param>
 /// <param name="version">The NuGet package version.</param>
 private void InstallPackage(IVsPackageInstaller installer, Project project, string package, string version)
 {
     _dte.StatusBar.Text = @"Installing " + package + "...";
     if (!string.IsNullOrEmpty(version))
         installer.InstallPackage("http://packages.nuget.org", project, package, version, false);
     else
         installer.InstallPackage("http://packages.nuget.org", project, package, (Version)null, false);
 }
コード例 #54
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            packageInstaller = ComponentModel.GetService<IVsPackageInstaller>();
            pkgInstallerServices = ComponentModel.GetService<IVsPackageInstallerServices>();
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if ( null != mcs )
            {
                // Create the command for the menu item.
                var cSharpProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidCSharpAddServiceStackReference);
                var cSharpProjectAddReferenceMenuCommand = new OleMenuCommand(CSharpAddReferenceCallback ,cSharpProjContextAddReferenceCommandId);
                cSharpProjectAddReferenceMenuCommand.BeforeQueryStatus += CSharpQueryAddMenuItem;
                mcs.AddCommand(cSharpProjectAddReferenceMenuCommand);

                var fSharpProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidFSharpAddServiceStackReference);
                var fSharpProjectContextOleMenuCommand = new OleMenuCommand(FSharpAddReferenceCallback, fSharpProjContextAddReferenceCommandId);
                fSharpProjectContextOleMenuCommand.BeforeQueryStatus += FSharpQueryAddMenuItem;
                mcs.AddCommand(fSharpProjectContextOleMenuCommand);

                var vbNetProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidVbNetAddServiceStackReference);
                var vbNetProjectContextOleMenuCommand = new OleMenuCommand(VbNetAddReferenceCallback, vbNetProjContextAddReferenceCommandId);
                vbNetProjectContextOleMenuCommand.BeforeQueryStatus += VbNetQueryAddMenuItem;
                mcs.AddCommand(vbNetProjectContextOleMenuCommand);

                var typeScriptProjContextAddReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidTypeScriptAddServiceStackReference);
                var typeScriptProjectContextOleMenuCommand = new OleMenuCommand(TypeScriptAddReferenceCallback, typeScriptProjContextAddReferenceCommandId);
                typeScriptProjectContextOleMenuCommand.BeforeQueryStatus += TypeScriptQueryAddMenuItem;
                mcs.AddCommand(typeScriptProjectContextOleMenuCommand);

                var updateReferenceCommandId = new CommandID(GuidList.guidVSServiceStackCmdSet, (int)PkgCmdIDList.cmdidUpdateServiceStackReference);
                var updateReferenceMenuCommand = new OleMenuCommand(UpdateReferenceCallback,
                    updateReferenceCommandId);
                updateReferenceMenuCommand.BeforeQueryStatus += QueryUpdateMenuItem;
                mcs.AddCommand(updateReferenceMenuCommand);
            }

            solutionEventsListener = new SolutionEventsListener();
            solutionEventsListener.OnAfterOpenSolution += SolutionLoaded;
        }
コード例 #55
0
        private void HandleCrmAssemblyProjects(Project project, IVsPackageInstaller installer)
        {
            try
            {
                //Install the proper NuGet packages based on the CRM SDK version and project types
                switch (_sdkVersion)
                {
                    case "CRM 2011 (5.0.X)":
                        InstallPackage(installer, project, "Microsoft.CrmSdk.CoreAssemblies", "5.0.18");
                        if (_crmProjectType == "Workflow")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Workflow", "5.0.18");
                        if (_needsClient == "True")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Extensions", "5.0.18");
                        break;
                    case "CRM 2013 (6.0.X)":
                        InstallPackage(installer, project, "Microsoft.CrmSdk.CoreAssemblies", "6.0.4");
                        if (_crmProjectType == "Workflow")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Workflow", "6.0.4");
                        if (_needsClient == "True")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Extensions", "6.0.4.1");
                        break;
                    case "CRM 2013 (6.1.X)":
                        InstallPackage(installer, project, "Microsoft.CrmSdk.CoreAssemblies", "6.1.1");
                        if (_crmProjectType == "Workflow")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Workflow", "6.1.1");
                        if (_needsClient == "True")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Extensions", "6.0.4.1");
                        break;
                    case "CRM 2015 (7.0.X)":
                        project.DTE.SuppressUI = true;
                        project.Properties.Item("TargetFrameworkMoniker").Value = ".NETFramework,Version=v4.5.2";
                        project = (Project)((Array)(_dte.ActiveSolutionProjects)).GetValue(0);
                        InstallPackage(installer, project, "Microsoft.CrmSdk.CoreAssemblies", "7.0.1");
                        if (_crmProjectType == "Workflow")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Workflow", "7.0.1");
                        if (_needsClient == "True")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Extensions", "7.0.0.1");
                        break;
                    case "CRM 2015 (7.1.X)":
                        project.DTE.SuppressUI = true;
                        project.Properties.Item("TargetFrameworkMoniker").Value = ".NETFramework,Version=v4.5.2";
                        project = (Project)((Array)(_dte.ActiveSolutionProjects)).GetValue(0);
                        InstallPackage(installer, project, "Microsoft.CrmSdk.CoreAssemblies", "7.1.1");
                        if (_crmProjectType == "Workflow")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Workflow", "7.1.1");
                        if (_needsClient == "True")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Extensions", "7.1.0");
                        break;
                    case "CRM 2016 (8.0.X)":
                        project.DTE.SuppressUI = true;
                        project.Properties.Item("TargetFrameworkMoniker").Value = ".NETFramework,Version=v4.5.2";
                        project = (Project)((Array)(_dte.ActiveSolutionProjects)).GetValue(0);
                        InstallPackage(installer, project, "Microsoft.CrmSdk.CoreAssemblies", null);
                        if (_crmProjectType == "Workflow")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Workflow", null);
                        if (_needsClient == "True")
                            InstallPackage(installer, project, "Microsoft.CrmSdk.Extensions", null);
                        break;
                }

                ExcludeSdkBinFolder(project);

                if (_crmProjectType == "Plug-in" || _crmProjectType == "Workflow")
                    GenerateNewKey(project);

                if (_isUnitTest != "True") return;

                InstallPackage(installer, project, "Moq", "4.2.1502.0911");
                if (_isNunit)
                {
                    InstallPackage(installer, project, "NUnitTestAdapter.WithFramework", "2.0.0");
                    AddSetting(project, "CRMTestType", "NUNIT");
                }
                else
                    AddSetting(project, "CRMTestType", "UNIT");

                ExcludePerformaceFolder(project);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Processing Template: " + ex.Message);
            }
        }
コード例 #56
0
ファイル: IFixtureMixin.cs プロジェクト: umaranis/Prig
 static void Realize(IVsPackageInstaller installer)
 {
     installer.InstallPackage(default(string), default(Project), default(string), default(string), default(bool));
     installer.InstallPackage(default(string), default(Project), default(string), default(Version), default(bool));
     installer.InstallPackagesFromRegistryRepository(default(string), default(bool), default(bool), default(Project), default(IDictionary<string, string>));
     installer.InstallPackagesFromRegistryRepository(default(string), default(bool), default(bool), default(bool), default(Project), default(IDictionary<string, string>));
     installer.InstallPackagesFromVSExtensionRepository(default(string), default(bool), default(bool), default(Project), default(IDictionary<string, string>));
     installer.InstallPackagesFromVSExtensionRepository(default(string), default(bool), default(bool), default(bool), default(Project), default(IDictionary<string, string>));
 }
コード例 #57
0
 public TestableVsTemplateWizard(
     IVsPackageInstaller installer = null,
     Func<string, XDocument> loadDocumentCallback = null,
     IVsWebsiteHandler websiteHandler = null,
     IVsPackageInstallerServices packageServices = null,
     IOutputConsoleProvider consoleProvider = null)
     : base(
         installer, 
         websiteHandler, 
         packageServices ?? new Mock<IVsPackageInstallerServices>().Object, 
         consoleProvider ?? new Mock<IOutputConsoleProvider>().Object,
         new Mock<IVsCommonOperations>().Object,
         new Mock<ISolutionManager>().Object)
 {
     ErrorMessages = new List<string>();
     _loadDocumentCallback = loadDocumentCallback ?? (path => null);
 }
コード例 #58
0
 public PackageServicesProxy(IVsPackageInstallerServices packageInstallerServices, IVsPackageInstaller packageInstaller, IVsPackageUninstaller packageUninstaller, IVsPackageSourceProvider packageSourceProvider)
 {
     _packageInstallerServices = packageInstallerServices;
     _packageInstaller = packageInstaller;
     _packageUninstaller = packageUninstaller;
     _packageSourceProvider = packageSourceProvider;
 }
コード例 #59
0
 public VsTemplateWizard(IVsPackageInstaller installer)
 {
     _installer = installer;
 }
        /// <summary>
        /// Installs one or more packages into the specified project.
        /// </summary>
        /// <param name="packageInstaller">The package installer service that performs the actual package installation.</param>
        /// <param name="project">The target project for installation.</param>
        /// <param name="configuration">The packages to install, where to install them from, and additional options for their installation.</param>
        /// <param name="repositorySettings">The repository settings for the packages being installed.</param>
        /// <param name="warningHandler">An action that accepts a warning message and presents it to the user, allowing execution to continue.</param>
        /// <param name="errorHandler">An action that accepts an error message and presents it to the user, allowing execution to continue.</param>
        internal void PerformPackageInstall(
            IVsPackageInstaller packageInstaller,
            Project project,
            PreinstalledPackageConfiguration configuration,
            Action<string> warningHandler,
            Action<string> errorHandler)
        {
            string repositoryPath = configuration.RepositoryPath;
            var failedPackageErrors = new List<string>();

            LegacyNuGet.IPackageRepository repository = configuration.IsPreunzipped
                                                ? (LegacyNuGet.IPackageRepository)new LegacyNuGet.UnzippedPackageRepository(repositoryPath)
                                                : (LegacyNuGet.IPackageRepository)new LegacyNuGet.LocalPackageRepository(repositoryPath);

            PreinstalledRepositoryProvider repos = new PreinstalledRepositoryProvider(errorHandler, _sourceProvider);
            repos.AddFromRepository(repository);

            // store expanded node state
            IDictionary<string, ISet<VsHierarchyItem>> expandedNodes = VsHierarchyHelper.GetAllExpandedNodes(_solutionManager);

            foreach (var package in configuration.Packages)
            {
                // Does the project already have this package installed?
                if (_packageServices.IsPackageInstalled(project, package.Id))
                {
                    // If so, is it the right version?
                    if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToNormalizedString()))
                    {
                        // No? Raise a warning (likely written to the Output window) and ignore this package.
                        warningHandler(String.Format(VsResources.PreinstalledPackages_VersionConflict, package.Id, package.Version));
                    }
                    // Yes? Just silently ignore this package!
                }
                else
                {
                    try
                    {
                        if (InfoHandler != null)
                        {
                            InfoHandler(String.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_PackageInstallStatus, package.Id, package.Version));
                        }

                        List<PackageIdentity> toInstall = new List<PackageIdentity>();
                        toInstall.Add(new PackageIdentity(package.Id, package.Version));

                        // Skip assembly references and disable binding redirections should be done together
                        bool disableBindingRedirects = package.SkipAssemblyReferences;

                        VSAPIProjectContext projectContext = new VSAPIProjectContext(package.SkipAssemblyReferences, disableBindingRedirects);

                        // Old templates have hardcoded non-normalized paths
                        projectContext.PackageExtractionContext.UseLegacyPackageInstallPath = true;

                        // This runs from the UI thread
                        PackageManagementHelpers.RunSync(async () => await _installer.InstallInternal(project, toInstall, repos, projectContext, package.IgnoreDependencies, CancellationToken.None));
                    }
                    catch (InvalidOperationException exception)
                    {
                        failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message);
                    }
                    catch (AggregateException aggregateEx)
                    {
                        var ex = aggregateEx.Flatten().InnerExceptions.FirstOrDefault();
                        if (ex is InvalidOperationException)
                        {
                            failedPackageErrors.Add(package.Id + "." + package.Version + " : " + ex.Message);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            if (failedPackageErrors.Any())
            {
                var errorString = new StringBuilder();
                errorString.AppendFormat(VsResources.PreinstalledPackages_FailedToInstallPackage, repositoryPath);
                errorString.AppendLine();
                errorString.AppendLine();
                errorString.Append(String.Join(Environment.NewLine, failedPackageErrors));

                errorHandler(errorString.ToString());
            }

            // RepositorySettings = null in unit tests
            if (EnvDTEProjectUtility.IsWebSite(project))
            {
                CreateRefreshFilesInBin(
                   project,
                   repositoryPath,
                   configuration.Packages.Where(p => p.SkipAssemblyReferences));

                CopyNativeBinariesToBin(project, repositoryPath, configuration.Packages);
            }

            // collapse nodes
            VsHierarchyHelper.CollapseAllNodes(_solutionManager, expandedNodes);
        }