Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created one console application to create visual studio project pragmatically, here i am not able install Nuget packages, always var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); statement returns null values. for your reference i added my code below. Help me to resolve this issue.

C#
static void Main(string[] args)
        {
            //InstallNuGetPackages.InstallNuGet("");
            string ProjectName = "WebAPIProj";
            string SolutionName = "EmptyTemplate";
            System.Type type = System.Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
            Object obj = System.Activator.CreateInstance(type, true);
            EnvDTE.DTE dte = (EnvDTE.DTE)obj;
            dte.MainWindow.Visible = true; // optional if you want to See VS doing its thing

            // create a new solution
            dte.Solution.Create("C:\\"+ SolutionName + "\\", SolutionName);
            var solution = dte.Solution;

            // create a C# WinForms app
            solution.AddFromTemplate(@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ProjectTemplatesCache\CSharp\Web\1033\EmptyWebApplicationProject40\EmptyWebApplicationProject40.vstemplate",
                @"C:\NewSolution\"+ ProjectName, ProjectName);
            InstallNuGetPackages.InstallNuGet(dte);

            foreach (var p in dte.Solution.Projects)
            {
              InstallNuGetPackages.InstallNuGet((Project)p, "Microsoft.AspNet.WebApi version1.1");
            }

            // save and quit
            dte.ExecuteCommand("File.SaveAll");
            dte.Quit();
        }


Code to install Nuget Packages

C#
public bool InstallNuGetPackage(Project project, string package)
    {
        bool installedPkg = true;
        try
        {
            var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); //Always this statement returns null
            IVsPackageInstallerServices installerServices = componentModel.GetService();
            if (!installerServices.IsPackageInstalled(project, package))
            {
                var installer = componentModel.GetService();
                installer.InstallPackage(null, project, package, (System.Version)null, false);
            }
        }
        catch (Exception ex)
        {
            installedPkg = false;
        }
        return installedPkg;
    }


What I have tried:

Not able to install Nuget packages pragmatically.
Posted
Updated 15-Mar-18 8:29am

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900