Ejemplo n.º 1
0
        public void Dispose()
        {
            if (this.solution != null && this.solutionEventsCookie != 0)
            {
                GC.SuppressFinalize(this);
                this.solution.UnadviseSolutionEvents(this.solutionEventsCookie);

                this.AfterSolutionLoaded = null;
                this.BeforeSolutionClosed = null;
                this.AfterSolutionClosed = null;

                this.solutionEventsCookie = 0;
                this.solution = null;
            }

            if (this.shell != null)
            {
                if (this.shellPropertyEventsCookie != 0)
                {
                    this.shell.UnadviseShellPropertyChanges(this.shellPropertyEventsCookie);
                    this.shellPropertyEventsCookie = 0;
                }

                if (this.broadcastMessageEventsCookie != 0)
                {
                    this.shell.UnadviseBroadcastMessages(this.broadcastMessageEventsCookie);
                    this.broadcastMessageEventsCookie = 0;
                }

                this.shell = null;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="LocatorWindowCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private LocatorWindowCommand(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            this.package = package;

            OleMenuCommandService commandService = ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (commandService != null)
            {
                var menuCommandID = new CommandID(CommandSet, CommandId);
                var menuItem = new MenuCommand(this.ShowToolWindow, menuCommandID);
                commandService.AddCommand(menuItem);
            }

            // Get the instance number 0 of this tool window. This window is single instance so this instance
            // is actually the only one.
            // The last flag is set to true so that if the tool window does not exists it will be created.
            _locatorWindow = package.FindToolWindow(typeof(LocatorWindow), 0, true) as LocatorWindow;
            if ((null == _locatorWindow) || (null == _locatorWindow.Frame))
            {
                throw new NotSupportedException("Cannot create tool window");
            }

            _locator = new Locator();
            _solution = ServiceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            _solution.AdviseSolutionEvents(_locator, out _cookie);
            _locatorWindow.SetLocator(_locator);
            _locator.StartWorkerThread();
        }
Ejemplo n.º 3
0
 public SolutionEventsListener(IVsSolution service, IVsSolutionBuildManager3 buildManager = null) {
     if (service == null) {
         throw new ArgumentNullException("service");
     }
     _solution = service;
     _buildManager = buildManager;
 }
Ejemplo n.º 4
0
        public VisualStudioProjectTracker(IServiceProvider serviceProvider)
        {
            _projectMap = new Dictionary<ProjectId, AbstractProject>();
            _projectPathToIdMap = new Dictionary<string, ProjectId>(StringComparer.OrdinalIgnoreCase);

            _serviceProvider = serviceProvider;
            _workspaceHosts = new List<WorkspaceHostState>(capacity: 1);

            _vsSolution = (IVsSolution)serviceProvider.GetService(typeof(SVsSolution));
            _runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));

            uint solutionEventsCookie;
            _vsSolution.AdviseSolutionEvents(this, out solutionEventsCookie);
            _solutionEventsCookie = solutionEventsCookie;

            // It's possible that we're loading after the solution has already fully loaded, so see if we missed the event
            var shellMonitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection));

            uint fullyLoadedContextCookie;
            if (ErrorHandler.Succeeded(shellMonitorSelection.GetCmdUIContextCookie(VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid, out fullyLoadedContextCookie)))
            {
                int fActive;
                if (ErrorHandler.Succeeded(shellMonitorSelection.IsCmdUIContextActive(fullyLoadedContextCookie, out fActive)) && fActive != 0)
                {
                    _solutionLoadComplete = true;
                }
            }
        }
Ejemplo n.º 5
0
        internal SolutionManager(DTE dte, IVsSolution vsSolution, IVsMonitorSelection vsMonitorSelection)
        {
            if (dte == null)
            {
                throw new ArgumentNullException("dte");
            }

            _initNeeded = true;
            _dte = dte;
            _vsSolution = vsSolution;
            _vsMonitorSelection = vsMonitorSelection;

            // Keep a reference to SolutionEvents so that it doesn't get GC'ed. Otherwise, we won't receive events.
            _solutionEvents = _dte.Events.SolutionEvents;

            // can be null in unit tests
            if (vsMonitorSelection != null)
            {
                Guid solutionLoadedGuid = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid;
                _vsMonitorSelection.GetCmdUIContextCookie(ref solutionLoadedGuid, out _solutionLoadedUICookie);

                uint cookie;
                int hr = _vsMonitorSelection.AdviseSelectionEvents(this, out cookie);
                ErrorHandler.ThrowOnFailure(hr);
            }
            
            _solutionEvents.BeforeClosing += OnBeforeClosing;
            _solutionEvents.AfterClosing += OnAfterClosing;
            _solutionEvents.ProjectAdded += OnProjectAdded;
            _solutionEvents.ProjectRemoved += OnProjectRemoved;
            _solutionEvents.ProjectRenamed += OnProjectRenamed;

            // Run the init on another thread to avoid an endless loop of SolutionManager -> Project System -> VSPackageManager -> SolutionManager
            ThreadPool.QueueUserWorkItem(new WaitCallback(Init));
        }
Ejemplo n.º 6
0
        public static void SelectItemInSolutionExplorer(this IVsUIShell uiShell, IVsSolution solution, string fileName)
        {
            HierarchyNodeIterator it = new HierarchyNodeIterator(solution);

            HierarchyNode hierarchyNode = it.FirstOrDefault(node => node.FullName == fileName);

            uiShell.SelectItemInSolutionExplorer(hierarchyNode);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Create an IItemContainer wrapper object against pHier
 /// </summary>
 internal static IItemContainer CreateItem(IServiceProvider serviceProvider, IVsSolution solution, IVsHierarchy pHier)
 {
     Debug.Assert(serviceProvider != null && solution != null && pHier != null);
     using (HierarchyNode current = new HierarchyNode(solution, pHier))
     {
         return CreateItem(serviceProvider, current);
     }
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Create an IItemContainer wrapper object against IVsSolution
 /// </summary>
 internal static IItemContainer CreateItem(IServiceProvider serviceProvider, IVsSolution solution, uint selectedItemid)
 {
     Debug.Assert(serviceProvider != null && solution != null);
     using (HierarchyNode parent = new HierarchyNode(solution))
     {
         return CreateItem(serviceProvider, parent, selectedItemid);
     }
 }
Ejemplo n.º 9
0
 public SolutionEventsListener(IServiceProvider serviceProvider)
 {
     solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
     if (solution != null)
     {
         solution.AdviseSolutionEvents(this, out solutionEventsCookie);
     }
 }
 public SolutionEventSinks()
 {
     solution = (IVsSolution)Package.GetGlobalService(typeof(SVsSolution));
     if (null == solution)
         Trace.WriteLine("Can't access solution service");
     else
         solution.AdviseSolutionEvents((IVsSolutionEvents)this, out solutionEventsCookie);
 }
        /// <summary>
        /// Constructor.
        /// Register Solution events.
        /// </summary>
        public SolutionChangeEventListener() {
            InitNullEvents();

            solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
            if(solution != null) {
                solution.AdviseSolutionEvents(this, out solutionEventsCookie);
            }
        }
Ejemplo n.º 12
0
 private void AdviceSolutionEvents()
 {
     solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
     if (solution != null)
     {
         ErrorHandler.ThrowOnFailure(solution.AdviseSolutionEvents(this, out solutionCookie));
     }
 }
Ejemplo n.º 13
0
 public ProjectNode(IVsSolution vsSolution, Guid projectGuid)
     : base(vsSolution, projectGuid)
 {
     this.project = this.Hierarchy as IVsProject;
     // Commented because it will show up an error dialog before getting back control to the recipe (caller)
     //Debug.Assert(project != null);  
     Debug.Assert(ItemId == VSConstants.VSITEMID_ROOT);
 }
Ejemplo n.º 14
0
 private void UnadviceSolutionEvents()
 {
     if (solution != null)
     {
         ErrorHandler.ThrowOnFailure(solution.UnadviseSolutionEvents(solutionCookie));
         solution = null;
     }
 }
Ejemplo n.º 15
0
        public SolutionEvents([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
        {
            Guard.NotNull(() => serviceProvider, serviceProvider);

            this.serviceProvider = serviceProvider;
            this.solution = serviceProvider.GetService<SVsSolution, IVsSolution>();
            this.solutionEvents = new VsSolutionEvents(this);
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(this.solution.AdviseSolutionEvents(this.solutionEvents, out this.solutionEventsCookie));
        }
 public ProjectItemsSynchronizer(Project sourceProject, Project targetProject, ILogger logger, IVsSolution solution, IHierarchyHelper hierarchyHelper, IProjectItemsFilter projectItemsFilter)
 {
     this.logger = logger;
     this.solution = solution;
     this.hierarchyHelper = hierarchyHelper;
     SourceProject = sourceProject;
     TargetProject = targetProject;
     this.projectItemsFilter = projectItemsFilter;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the SolutionListener class.
        /// </summary>
        /// <param name="serviceProvider">The system service provider.</param>
        internal SolutionListener(IServiceProvider serviceProvider)
        {
            Param.AssertNotNull(serviceProvider, "serviceProvider");

            this.solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            if (this.solution == null)
            {
                throw new InvalidOperationException();
            }
        }
        public SolutionEventListener([Import(typeof (SVsServiceProvider))] IServiceProvider serviceProvider)
        {
            ValidateArg.NotNull(serviceProvider, "serviceProvider");
            _solution = (IVsSolution) serviceProvider.GetService(typeof (IVsSolution));

            if (_solution != null)
            {
                _solution.AdviseSolutionEvents(this, out _solutionEventsCookie);
            }
        }
Ejemplo n.º 19
0
        protected SolutionListener(IServiceProvider serviceProviderParameter)
        {
            Utilities.ArgumentNotNull("serviceProviderParameter", serviceProviderParameter);

            this.serviceProvider = serviceProviderParameter;
            this.solution = this.serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;

            Debug.Assert(this.solution != null, "Could not get the IVsSolution object from the services exposed by this project");
            Utilities.CheckNotNull(this.solution);
        }
Ejemplo n.º 20
0
 public void Dispose()
 {
     if (solution != null && solutionEventsCookie != 0)
     {
         GC.SuppressFinalize(this);
         solution.UnadviseSolutionEvents(solutionEventsCookie);
         OnAfterOpenSolution = null;
         solutionEventsCookie = 0;
         solution = null;
     }
 }
Ejemplo n.º 21
0
 public SolutionEvent(ServiceProvider sp)
 {
     serviceProvider = sp;
     solution = (IVsSolution)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IVsSolution));
     dte = (EnvDTE.DTE)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE));
     //serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
     if (solution != null)
     {
         solution.AdviseSolutionEvents(this, out solutionEventsCookie);
     }
 }
Ejemplo n.º 22
0
        public SolutionEventsListener(IServiceProvider serviceProvider)
        {
            solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            solution?.AdviseSolutionEvents(this, out solutionEventsCookie);

            buildManager = serviceProvider.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager3;
            buildManager?.AdviseUpdateSolutionEvents3(this, out updateSolutionEventsCookie);

            monitorSelection = serviceProvider.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
            monitorSelection?.AdviseSelectionEvents(this, out selectionEventsCoockie);
        }
Ejemplo n.º 23
0
        public SolutionEventsListener(IServiceProvider serviceProvider) {
            if (serviceProvider == null) {
                throw new ArgumentNullException("serviceProvider");
            }

            _solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
            if (_solution == null) {
                throw new InvalidOperationException("Cannot get solution service");
            }
            _buildManager = serviceProvider.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager3;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="VisualStudioJSLintProvider" /> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="errorListProvider">The error list provider.</param>
        /// <param name="jsLintFactory">The JSLint factory.</param>
        /// <param name="fileSystemWrapper">The file system wrapper.</param>
        /// <param name="settingsRepository">The settings repository.</param>
        /// <param name="cacheProvider">The cache provider.</param>
        public VisualStudioJSLintProvider(IServiceProvider serviceProvider, IJSLintErrorListProvider errorListProvider, IJSLintFactory jsLintFactory, IFileSystemWrapper fileSystemWrapper, ISettingsRepository settingsRepository, ICacheProvider cacheProvider)
        {
            this.serviceProvider = serviceProvider;
            this.errorListProvider = errorListProvider;
            this.jsLintFactory = jsLintFactory;
            this.fileSystemWrapper = fileSystemWrapper;
            this.settingsRepository = settingsRepository;
            this.cacheProvider = cacheProvider;

            this.statusBar = this.serviceProvider.GetService<SVsStatusbar, IVsStatusbar>();
            this.solutionService = this.serviceProvider.GetService<SVsSolution, IVsSolution>();
        }
 /// <summary>The dispose.</summary>
 public void Dispose()
 {
     if (this.solution != null && this.solutionEventsCookie != 0)
     {
         GC.SuppressFinalize(this);
         this.solution.UnadviseSolutionEvents(this.solutionEventsCookie);
         this.OnQueryUnloadProject = null;
         this.OnAfterOpenProject = null;
         this.solutionEventsCookie = 0;
         this.solution = null;
     }
 }
 public void Dispose()
 {
     if (solution != null && solutionEventsCookie != 0)
     {
         GC.SuppressFinalize(this);
         solution.UnadviseSolutionEvents(solutionEventsCookie);
         AfterSolutionLoaded = null;
         BeforeSolutionClosed = null;
         solutionEventsCookie = 0;
         solution = null;
     }
 }
Ejemplo n.º 27
0
        protected SolutionListener(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
            this.solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;

            Debug.Assert(this.solution != null, "Could not get the IVsSolution object from the services exposed by this project");

            if (this.solution == null)
            {
                throw new InvalidOperationException();
            }
        }
        protected SolutionListener(IServiceProvider serviceProviderParameter) {
            if (serviceProviderParameter == null) {
                throw new ArgumentNullException("serviceProviderParameter");
            }

            this.serviceProvider = serviceProviderParameter;
            this.solution = this.serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;

            if (this.solution == null) {
                throw new InvalidOperationException("Could not get the IVsSolution object from the services exposed by this project");
            }
        }
        /// <summary>Initializes a new instance of the <see cref="SolutionEventsListener"/> class.</summary>
        public SolutionEventsListener(IVsEnvironmentHelper helper)
        {
            this.environment = helper;
            this.InitNullEvents();

            this.solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;

            if (this.solution != null)
            {
                this.solution.AdviseSolutionEvents(this, out this.solutionEventsCookie);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Saves or Save Asthe project.
        /// </summary>
        /// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param>
        /// <param name="fileName">The name of the project file.</param>
        private void DoSave(bool isCalledFromSaveAs, string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            if (this.project == null || this.project.Site == null || this.project.IsClosed)
            {
                throw new InvalidOperationException();
            }

            using (AutomationScope scope = new AutomationScope(this.project.Site))
            {
                // If an empty file name is passed in for Save then make the file name the project name.
                if (!isCalledFromSaveAs && string.IsNullOrEmpty(fileName))
                {
                    // Use the solution service to save the project file. Note that we have to use the service
                    // so that all the shell's elements are aware that we are inside a save operation and
                    // all the file change listenters registered by the shell are suspended.

                    // Get the cookie of the project file from the RTD.
                    IVsRunningDocumentTable rdt = this.project.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
                    if (null == rdt)
                    {
                        throw new InvalidOperationException();
                    }

                    IVsHierarchy hier;
                    uint         itemid;
                    IntPtr       unkData;
                    uint         cookie;
                    ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.project.Url, out hier,
                                                                        out itemid, out unkData, out cookie));
                    if (IntPtr.Zero != unkData)
                    {
                        Marshal.Release(unkData);
                    }

                    // Verify that we have a cookie.
                    if (0 == cookie)
                    {
                        // This should never happen because if the project is open, then it must be in the RDT.
                        throw new InvalidOperationException();
                    }

                    // Get the IVsHierarchy for the project.
                    IVsHierarchy prjHierarchy = HierarchyNode.GetOuterHierarchy(this.project);

                    // Now get the soulution.
                    IVsSolution solution = this.project.Site.GetService(typeof(SVsSolution)) as IVsSolution;
                    // Verify that we have both solution and hierarchy.
                    if ((null == prjHierarchy) || (null == solution))
                    {
                        throw new InvalidOperationException();
                    }

                    ErrorHandler.ThrowOnFailure(solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, prjHierarchy, cookie));
                }
                else
                {
                    // We need to make some checks before we can call the save method on the project node.
                    // This is mainly because it is now us and not the caller like in  case of SaveAs or Save that should validate the file name.
                    // The IPersistFileFormat.Save method only does a validation that is necesseray to be performed. Example: in case of Save As the
                    // file name itself is not validated only the whole path. (thus a file name like file\file is accepted, since as a path is valid)

                    // 1. The file name has to be valid.
                    string fullPath = fileName;
                    try
                    {
                        if (!Path.IsPathRooted(fileName))
                        {
                            fullPath = Path.Combine(this.project.ProjectFolder, fileName);
                        }
                    }
                    // We want to be consistent in the error message and exception we throw. fileName could be for example #¤&%"¤&"%  and that would trigger an ArgumentException on Path.IsRooted.
                    catch (ArgumentException)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
                    }

                    // It might be redundant but we validate the file and the full path of the file being valid. The SaveAs would also validate the path.
                    // If we decide that this is performance critical then this should be refactored.
                    Utilities.ValidateFileName(this.project.Site, fullPath);

                    if (!isCalledFromSaveAs)
                    {
                        // 2. The file name has to be the same
                        if (!NativeMethods.IsSamePath(fullPath, this.project.Url))
                        {
                            throw new InvalidOperationException();
                        }

                        ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 1, 0));
                    }
                    else
                    {
                        ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 0, 0));
                    }
                }
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Verifies if a single object is selected
        /// </summary>
        /// <param name="hierarchy">Current selected project hierarchy</param>
        /// <param name="itemid">ID of the selected item</param>
        /// <returns>True if a single item is selected</returns>
        public static bool IsSingleProjectItemSelection(out IVsHierarchy hierarchy, out uint itemid)
        {
            hierarchy = null;
            itemid    = VSConstants.VSITEMID_NIL;
            int hr = VSConstants.S_OK;

            IVsMonitorSelection monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
            IVsSolution         solution         = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;

            if (monitorSelection == null || solution == null)
            {
                return(false);
            }

            IVsMultiItemSelect multiItemSelect       = null;
            IntPtr             hierarchyPtr          = IntPtr.Zero;
            IntPtr             selectionContainerPtr = IntPtr.Zero;

            try
            {
                hr = monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainerPtr);

                if (ErrorHandler.Failed(hr) || hierarchyPtr == IntPtr.Zero || itemid == VSConstants.VSITEMID_NIL)
                {
                    // there is no selection
                    return(false);
                }

                if (multiItemSelect != null)
                {
                    // multiple items are selected
                    return(false);
                }

                if (itemid == VSConstants.VSITEMID_ROOT)
                {
                    // there is a hierarchy root node selected, thus it is not a single item inside a project
                    return(false);
                }

                hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy;
                if (hierarchy == null)
                {
                    return(false);
                }

                Guid guidProjectID = Guid.Empty;

                if (ErrorHandler.Failed(solution.GetGuidOfProject(hierarchy, out guidProjectID)))
                {
                    return(false); // hierarchy is not a project inside the Solution if it does not have a ProjectID Guid
                }

                // if we got this far then there is a single project item selected
                return(true);
            }
            finally
            {
                if (selectionContainerPtr != IntPtr.Zero)
                {
                    Marshal.Release(selectionContainerPtr);
                }

                if (hierarchyPtr != IntPtr.Zero)
                {
                    Marshal.Release(hierarchyPtr);
                }
            }
        }
Ejemplo n.º 32
0
        public static IEnumerable <IVsHierarchy> GetProjectHierarchies(this IVsSolution solution)
        {
            Contract.Requires(solution != null);

            return(GetProjectHierarchies(solution, __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION));
        }
 public ProjectWithPackageConfigConverter(Project project, IVsPackageInstallerServices packageInstaller, IVsSolution vsSolution)
 {
     PackageConfigFilePath = project.GetPackageConfigFilePath();
     ProjectFolder         = project.GetProjectRootPath();
     ProjectFileName       = project.GetProjectFileName();
     ProjectFullName       = project.FullName;
     PropertiesFolder      = project.GetPropertiesFolderPath();
     AssemblyInfoFilePath  = project.GetAssemblyInfoPath();
     VsSolution            = vsSolution;
     DteProject            = project;
     PackageInstaller      = packageInstaller;
     BackupFolderName      = $"backup-{DateTime.UtcNow.ToString("yyyy-MM-dd-hhmmss")}";
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Rather than directly creating the project, ask VS to initate the process of
        /// creating an aggregated project in case we are flavored. We will be called
        /// on the IVsAggregatableProjectFactory to do the real project creation.
        /// </summary>
        /// <param name="fileName">Project file</param>
        /// <param name="location">Path of the project</param>
        /// <param name="name">Project Name</param>
        /// <param name="flags">Creation flags</param>
        /// <param name="projectGuid">Guid of the project</param>
        /// <param name="project">Project that end up being created by this method</param>
        /// <param name="canceled">Was the project creation canceled</param>
        protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled)
        {
            project  = IntPtr.Zero;
            canceled = 0;

            if ((flags & ((uint)__VSCREATEPROJFLAGS2.CPF_DEFERREDSAVE)) != 0)
            {
                throw new NotSupportedException(SR.GetString(SR.NoZeroImpactProjects));
            }

            if ((flags & ((uint)__VSCREATEPROJFLAGS.CPF_OPENFILE)) != 0)
            {
                if (new ProjectInspector(fileName).IsPoisoned(Site))
                {
                    // error out
                    int ehr = unchecked ((int)0x80042003); // VS_E_INCOMPATIBLEPROJECT
                    ErrorHandler.ThrowOnFailure(ehr);
                }
            }

            // Solution properties
            IVsSolution solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution;

            Debug.Assert(solution != null, "Could not retrieve the solution service from the global service provider");

            // We do not want to throw. If we cannot set the solution related constants we set them to empty string.
            string solutionDirectory, solutionPath, userOptionsFile;

            solution.GetSolutionInfo(out solutionDirectory, out solutionPath, out userOptionsFile);
            if (solutionDirectory == null)
            {
                solutionDirectory = String.Empty;
            }
            if (solutionPath == null)
            {
                solutionPath = String.Empty;
            }
            string solutionFileName  = (solutionPath.Length == 0) ? String.Empty : Path.GetFileName(solutionPath);
            string solutionName      = (solutionPath.Length == 0) ? String.Empty : Path.GetFileNameWithoutExtension(solutionPath);
            var    solutionExtension = Path.GetExtension(solutionPath);

            // DevEnvDir property
            IVsShell shell = this.Site.GetService(typeof(SVsShell)) as IVsShell;

            Debug.Assert(shell != null, "Could not retrieve the IVsShell service from the global service provider");
            object installDirAsObject;

            // We do not want to throw. If we cannot set the solution related constants we set them to empty string.
            shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out installDirAsObject);
            string installDir = ((string)installDirAsObject);

            if (String.IsNullOrEmpty(installDir))
            {
                installDir = String.Empty;
            }
            else
            {
                // Ensure that we have trailing backslash as this is done for the langproj macros too.
                if (installDir[installDir.Length - 1] != Path.DirectorySeparatorChar)
                {
                    installDir += Path.DirectorySeparatorChar;
                }
            }

            // Get the list of GUIDs from the project/template
            string guidsList = this.ProjectTypeGuids(fileName);

            // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation)
            IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject));
            int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project);

            if (hr == VSConstants.E_ABORT)
            {
                canceled = 1;
            }
            ErrorHandler.ThrowOnFailure(hr);

            this.buildProject = null;
        }
Ejemplo n.º 35
0
        public MessageHelper(IVsSolution vsSolution, ErrorListProvider errorList)
        {
            VsSolution = vsSolution;

            ErrorList = errorList;
        }
Ejemplo n.º 36
0
 public SolutionEventsService(IVsSolution solution)
 {
     _solution = solution;
     _solution.AdviseSolutionEvents(this, out _solutionCookie);
 }
Ejemplo n.º 37
0
        private void dialog_OnProxyEntered(object sender, ProxyEntryInformation pInfo)
        {
            // Get active project
            DTE     dte           = (DTE)GetService(typeof(DTE));
            Project activeProject = (dte.ActiveSolutionProjects as Array).GetValue(0) as EnvDTE.Project;

            // Get current solution
            IVsSolution solution = GetService(typeof(IVsSolution)) as IVsSolution;
            // Get WCF Service references
            uint itemId = VSConstants.VSITEMID_NIL;

            IVsWCFReferenceGroupCollection serviceReferences = this.GetWCFServices(solution.GetSelectedHierarchy(out itemId));

            // Create project file variables
            string        languageFileExtension = GetLanguageFileExtension(activeProject);
            string        projectFile           = activeProject.FullName;                                                                                                                                         // C:\MySampleApp\MySampleApp\MySampleApp.csproj
            string        generatedCodeFilePath = string.Format(@"{0}\{1}\{2}\{2}.proxy.{3}", Path.GetDirectoryName(projectFile), ProxyMgrConstants.PackageFolderName, pInfo.ServiceName, languageFileExtension); //C:\MySampleApp\MySampleApp\Service Proxies\Input\
            string        svcmapFilePath        = string.Format(@"{0}\{1}{2}", Path.GetDirectoryName(generatedCodeFilePath), pInfo.ServiceName, ProxyMgrConstants.SvcmapFileExtension);
            List <string> itemsToCheckout       = new List <string>(2);
            FileStream    svcMapStream          = null;

            // Log
            LogWriter.WriteLine(@"****************** PROXY GENERATION STARTED: " + pInfo.ServiceAddress + " ******************");
            LogWriter.WriteLine("[ OK ] State: " + (pInfo.IsAddContext ? "Add" : "Configure"));
            LogWriter.WriteLine("[ OK ] CodeFilePath: " + generatedCodeFilePath);
            LogWriter.WriteLine("[ OK ] MapFilePath : " + svcmapFilePath);

            // if intended service not exists
            if (serviceReferences.GetReferenceGroupByName(pInfo.ServiceName, pInfo.ServiceName) == null)
            {
                if (!Directory.Exists(Path.GetDirectoryName(generatedCodeFilePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(generatedCodeFilePath));
                }

                svcMapStream = File.Create(svcmapFilePath);
                this.CheckOutItems(dte, projectFile);
            }
            else
            {
                if (pInfo.IsAddContext)
                {
                    // Service proxy exists
                    ShowError("[ FAIL ] Intended Service Reference name is exists. Please enter another name for proxy!");
                    return;
                }

                if (!File.Exists(svcmapFilePath))
                {
                    // Something went worng error
                    ShowError("[ FAIL ] Service mapping file is missing. Check path: " + svcmapFilePath);
                    return;
                }

                this.CheckOutItems(dte, svcmapFilePath, generatedCodeFilePath);
                svcMapStream = File.Open(svcmapFilePath, FileMode.Truncate, FileAccess.Write);
            }

            using (svcMapStream)
                svcMapStream.Serialize(pInfo);

            // Generate code
            this.GenerateServiceProxy(activeProject, pInfo);

            if (pInfo.IsAddContext)
            {
                this.ManipulateProjectFile(projectFile, (serviceReferences.Count() > 0), languageFileExtension, pInfo.ServiceName);
            }

            // Save the project!!!
            activeProject.Save();

            // Reload project
            this.Reload(activeProject);
        }
Ejemplo n.º 38
0
    private static IVsHierarchy CreateHierarchy(HierarchyData data, IVsSolution solution)
    {
        Mock <IVsHierarchy> hierarchy;
        object nameAsObject;
        string canonicalName;


        hierarchy = new Mock <IVsHierarchy>();

        SetClassID(hierarchy, data.CLSID);

        nameAsObject = data.Name;

        switch (data.Type)
        {
        case HierarchyType.Solution:
            canonicalName = Path.Combine(SolutionRoot, data.Name + ".sln");
            break;

        case HierarchyType.Project:
        case HierarchyType.UnloadedProject:
            canonicalName = Path.Combine(SolutionRoot, data.Name, data.Name + (data.IsShared ? ".shproj" : ".csproj"));
            break;

        default:
            canonicalName = data.Identifier.ToString();
            break;
        }

        hierarchy
        .Setup((x) => x.GetCanonicalName((uint)VSConstants.VSITEMID.Root, out canonicalName))
        .Returns(VSConstants.S_OK);

        hierarchy
        .Setup((x) => x.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_Name, out nameAsObject))
        .Returns(VSConstants.S_OK);

        hierarchy
        .Setup((x) => x.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ParentHierarchy, out It.Ref <object> .IsAny))
        .Returns(new GetPropertyCallback((uint itemID, int property, out object?value) => {
            Guid parentIdentifier;


            if (data.Parent is null)
            {
                value = null;
                return(VSConstants.S_OK);
            }

            parentIdentifier = data.Parent.Value;

            if (ErrorHandler.Succeeded(solution.GetProjectOfGuid(ref parentIdentifier, out IVsHierarchy parent)))
            {
                value = parent;
                return(VSConstants.S_OK);
            }

            value = null;
            return(VSConstants.E_FAIL);
        }));

        hierarchy
        .Setup((x) => x.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemsImportFullPaths, out It.Ref <object> .IsAny))
        .Returns(new GetPropertyCallback((uint itemID, int property, out object?value) => {
            List <HierarchyData> dependencies;


            dependencies = data.GetDependencyData().Where((x) => x.IsShared).ToList();

            if (dependencies.Count > 0)
            {
                value = string.Join(
                    "|",
                    dependencies.Select((x) => Path.Combine(SolutionRoot, x.Name, x.Name + ".projitems"))
                    );
                return(VSConstants.S_OK);
            }

            value = null;
            return(VSConstants.E_FAIL);
        }));


        if (data.IsProject)
        {
            hierarchy.As <IVsProject>();
        }

        return(hierarchy.Object);
    }
Ejemplo n.º 39
0
 public ProjectNode(IVsSolution vsSolution, Guid projectGuid)
     : base(vsSolution, projectGuid)
 {
     this.project = this.Hierarchy as IVsProject;
     Debug.Assert(ItemId == VSConstants.VSITEMID_ROOT);
 }
Ejemplo n.º 40
0
 public SolutionsEventsHandler(IVsSolution sln) : base(sln)
 {
 }
Ejemplo n.º 41
0
 public SolutionEventsListener([Import(typeof(IServiceProvider))] IServiceProvider serviceProvider)
 {
     this.solution = serviceProvider.GetService <IVsSolution>(typeof(SVsSolution));
 }
Ejemplo n.º 42
0
        private void TestImplicitNestedProjectReload(IServiceProvider sp, ProjectNode project, int dialogAnswer)
        {
            // Save everything.
            IVsSolution solutionService = (IVsSolution)sp.GetService(typeof(IVsSolution));

            solutionService.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, project, 0);

            IVsProject3 nestedProject = Utilities.GetNestedHierarchy(project, "ANestedProject") as IVsProject3;

            if (nestedProject == null)
            {
                throw new InvalidOperationException("The nested project has not been loaded corectly");
            }

            string nestedProjectFileName = null;

            nestedProject.GetMkDocument(VSConstants.VSITEMID_ROOT, out nestedProjectFileName);

            if (nestedProjectFileName == null)
            {
                throw new InvalidOperationException("The nested project file name could not been retrieved corectly");
            }

            string resourceText = Utilities.GetResourceStringFromTheProjectAssembly("QueryReloadNestedProject");

            // Create the messageBoxListener Thread. This will bring up the reload of the nested project file.
            // In this scenario we will answer dialogAnswer. Also we rely on the exact messagebox text here.
            string message = String.Format(System.Globalization.CultureInfo.CurrentCulture, resourceText, nestedProjectFileName);

            DialogBoxPurger purger = new DialogBoxPurger(dialogAnswer, message);
            bool            result = false;

            try
            {
                purger.Start();
                this.AddReferenceExternallyToTheProjectFile(nestedProjectFileName);
            }
            finally
            {
                result = purger.WaitForDialogThreadToTerminate();
            }

            if (!result)
            {
                throw new InvalidOperationException("The messagebox for relaoding the nested project file has never popped up");
            }

            // Check to see if the nested project is there.
            EnvDTE.Project     projectDTE = Utilities.GetAutomationObject(project);
            EnvDTE.ProjectItem item       = projectDTE.ProjectItems.Item("ANestedProject");

            Assert.IsNotNull(item, "The nested project has not been loaded correctly.");
            EnvDTE.Project nestedAutomationProject = item.SubProject;

            // Now check to see if we can find the added reference
            VSLangProj.VSProject automationProject = nestedAutomationProject.Object as VSLangProj.VSProject;
            if (nestedAutomationProject == null)
            {
                throw new InvalidOperationException("The nested project is not a vs language project");
            }

            // Get references collection
            VSLangProj.References references = automationProject.References;

            IEnumerator enumerator = references.GetEnumerator();
            bool        found      = false;

            while (enumerator.MoveNext())
            {
                VSLangProj.Reference reference = enumerator.Current as VSLangProj.Reference;
                if (reference.Name == BuildEngineRef)
                {
                    found = true;
                }
            }

            if (dialogAnswer == NativeMethods.IDYES)
            {
                Assert.IsTrue(found, "The nested project file has not been reloaded correctly");
            }
            else
            {
                Assert.IsFalse(found, "The nested project file has been reloaded but was asked not to do that.");
            }
        }
Ejemplo n.º 43
0
        internal Microsoft.Build.Evaluation.Project ReinitializeMsBuildProject(string filename)
        {
            // Solution properties
            IVsSolution solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution;

            Debug.Assert(solution != null, "Could not retrieve the solution service from the global service provider");

            // We do not want to throw.If we cannot set the solution related constants we set them to empty string.
            string solutionDirectory, solutionPath, userOptionsFile;

            solution.GetSolutionInfo(out solutionDirectory, out solutionPath, out userOptionsFile);
            if (solutionDirectory == null)
            {
                solutionDirectory = String.Empty;
            }
            if (solutionPath == null)
            {
                solutionPath = String.Empty;
            }
            string solutionFileName  = (solutionPath.Length == 0) ? String.Empty : Path.GetFileName(solutionPath);
            string solutionName      = (solutionPath.Length == 0) ? String.Empty : Path.GetFileNameWithoutExtension(solutionPath);
            string solutionExtension = String.Empty;

            if (solutionPath.Length > 0 && Path.HasExtension(solutionPath))
            {
                solutionExtension = Path.GetExtension(solutionPath);
            }

            //DevEnvDir property
            IVsShell shell = this.Site.GetService(typeof(SVsShell)) as IVsShell;

            Debug.Assert(shell != null, "Could not retrieve the IVsShell service from the global service provider");
            object installDirAsObject;

            //We do not want to throw.If we cannot set the solution related constants we set them to empty string.
            shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out installDirAsObject);
            string installDir = ((string)installDirAsObject);

            if (String.IsNullOrEmpty(installDir))
            {
                installDir = String.Empty;
            }
            else
            {
                //Ensure that we have trailing backslash as this is done for the langproj macros too.
                if (installDir[installDir.Length - 1] != Path.DirectorySeparatorChar)
                {
                    installDir += Path.DirectorySeparatorChar;
                }
            }

            var projectGlobalPropertiesThatAllProjectSystemsMustSet = new Dictionary <string, string>()
            {
                { GlobalProperty.SolutionDir.ToString(), solutionDirectory },
                { GlobalProperty.SolutionPath.ToString(), solutionPath },
                { GlobalProperty.SolutionFileName.ToString(), solutionFileName },
                { GlobalProperty.SolutionName.ToString(), solutionName },
                { GlobalProperty.SolutionExt.ToString(), solutionExtension },
                { GlobalProperty.BuildingInsideVisualStudio.ToString(), "true" },
                { GlobalProperty.Configuration.ToString(), "" },
                { GlobalProperty.Platform.ToString(), "" },
                { GlobalProperty.DevEnvDir.ToString(), installDir }
            };

            return(Utilities.ReinitializeMsBuildProject(this.buildEngine, filename, projectGlobalPropertiesThatAllProjectSystemsMustSet, this.buildProject));
        }
Ejemplo n.º 44
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 async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
#if DEBUG
            if (Environment.GetEnvironmentVariable("DominoDebugVsPackageOnStart") == "1")
            {
                System.Diagnostics.Debugger.Launch();
            }
#endif

            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", ToString()));
            await base.InitializeAsync(cancellationToken, progress);

            // do the rest on the UI thread
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            // Create and register our factory
            RegisterProjectFactory(new ProjectFlavorFactory(this));

            var outWindow = GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
            Debug.Assert(outWindow != null, "outWindow != null");

            // Setup a pane for VsPackage messages
            var vsPackagePaneGuid = VsPackagePaneGuid;
            var hResult           = outWindow.CreatePane(ref vsPackagePaneGuid, VsPackagePaneName, 1, 0);
            Marshal.ThrowExceptionForHR(hResult);

            hResult = outWindow.GetPane(ref vsPackagePaneGuid, out m_packageOutputPane);
            Marshal.ThrowExceptionForHR(hResult);

            PrintDebugMessage(Strings.DebugMessageDominoPackgeLoading);

            try
            {
                // Modifying events to listen to Add/Remove/Rename items
                m_dte = await GetServiceAsync(typeof(DTE)) as DTE;

                // Setup output pane
                var buildOutputPaneGuid = VSConstants.GUID_BuildOutputWindowPane;
                outWindow.GetPane(ref buildOutputPaneGuid, out m_buildOutputPane);

                // Register solution events (required especially when projects are loaded and unloaded)
                m_vsSolutionEvents = new SolutionEventsHandler(this);
                m_vsSolution       = await GetServiceAsync(typeof(SVsSolution)) as IVsSolution;

                ErrorHandler.ThrowOnFailure(m_vsSolution.AdviseSolutionEvents(m_vsSolutionEvents, out m_solutionEventsCookie));
                ErrorHandler.ThrowOnFailure(m_vsSolution.AdviseSolutionEvents(this, out m_solutionEventsCookie));

                // Initializing an error list to be used for showing errors
                m_shellOpenDocument = GetGlobalService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
                m_textManager       = GetGlobalService(typeof(VsTextManagerClass)) as IVsTextManager;
                m_errorListProvider = new ErrorListProvider(this)
                {
                    ProviderName = "Build Accelerator",
                    ProviderGuid = new Guid("5A10E43F-8D1D-4026-98C0-E6B502058901"),
                };

                // Sets the global property to verify whether BuildXL package is installed inside Visual studio or not
                // This helps making the installation of BuildXLVsPackage mandatory
                var globalcollection = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection;
                globalcollection.SetGlobalProperty(Constants.DominoPackageInstalled, "true");

                // Helps to ensures to force all users to upgrade to the latest version
                SetDominoPackageVersion(globalcollection);

                // Iterate through projects and add events to each project in the solution
                foreach (Project project in GetAllProjects(m_dte.Solution))
                {
                    HandleProject(project);
                }

                PrintDebugMessage(Strings.DebugMessageDominoPackageLoadedSuccessful);
            }
            catch (Exception e)
            {
                PrintDebugMessage(Strings.DebugMessageDominoPackageLoadFailure, e);
                throw;
            }
        }
Ejemplo n.º 45
0
        public int UpgradeProject(string xprojLocation, uint upgradeFlags, string backupDirectory, out string migratedProjectFileLocation,
                                  IVsUpgradeLogger logger, out int upgradeRequired, out Guid migratedProjectGuid)
        {
            UIThreadHelper.VerifyOnUIThread();
            bool   success     = false;
            string projectName = Path.GetFileNameWithoutExtension(xprojLocation);
            int    hr          = UpgradeProject_CheckOnly(xprojLocation, logger, out upgradeRequired, out migratedProjectGuid, out uint dummy);

            // This implementation can only return S_OK. Throw if it returned something else.
            Verify.HResult(hr);

            // First, we back up the project. This function will take care of logging any backup failures.
            if (!BackupProject(backupDirectory, xprojLocation, projectName, logger))
            {
                migratedProjectFileLocation = xprojLocation;
                return(VSConstants.VS_E_PROJECTMIGRATIONFAILED);
            }

            IVsSolution solution = _serviceProvider.GetService <IVsSolution, SVsSolution>();

            Verify.HResult(solution.GetSolutionInfo(out string solutionDirectory, out string solutionFile, out string userOptsFile));

            HResult backupResult = BackupAndDeleteGlobalJson(solutionDirectory, solution, backupDirectory, xprojLocation, projectName, logger);

            if (!backupResult.Succeeded)
            {
                migratedProjectGuid         = GetType().GUID;
                migratedProjectFileLocation = xprojLocation;
                return(backupResult);
            }

            string directory = Path.GetDirectoryName(xprojLocation);

            (string logFile, int processExitCode) = MigrateProject(solutionDirectory, directory, xprojLocation, projectName, logger);

            if (!string.IsNullOrEmpty(logFile))
            {
                (migratedProjectFileLocation, success) = LogReport(logFile, processExitCode, projectName, xprojLocation, logger);
            }
            else
            {
                migratedProjectGuid         = GetType().GUID;
                migratedProjectFileLocation = null;
            }

            if (string.IsNullOrEmpty(migratedProjectFileLocation))
            {
                // If we weren't able to find a new csproj, something went very wrong, and dotnet migrate is doing something that we don't expect.
                migratedProjectGuid = GetType().GUID;
                Assumes.NotNullOrEmpty(migratedProjectFileLocation);
                migratedProjectFileLocation = xprojLocation;
                success = false;
            }

            if (success)
            {
                CleanupXproj(directory, projectName);
            }

            return(success ? VSConstants.S_OK : VSConstants.VS_E_PROJECTMIGRATIONFAILED);
        }
Ejemplo n.º 46
0
 public static bool HasFile(this IVsSolution solution, string file)
 {
     return(solution.GetLoadedProjects().Any(p => p.HasFile(file)));
 }
 public TestableProjectLinkTracker(IVsTrackProjectDocuments2 documentTracker, IVsSolution solution)
     : base(documentTracker, solution, new MockLogger())
 {
 }
Ejemplo n.º 48
0
 public static IEnumerable <IVsProject> GetLoadedProjects(this IVsSolution solution)
 {
     return(solution.EnumerateLoadedProjects(__VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION).OfType <IVsProject>());
 }
Ejemplo n.º 49
0
        public static (string slnDir, string slnFile, string userOptsFile) GetSolutionInfo(this IVsSolution @this)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var hresult = @this.GetSolutionInfo(out var slnDir, out var slnFile, out var userOptsFile);

            if (hresult != VSConstants.S_OK)
            {
                throw new COMException("GetSolutionInfo failed", hresult);
            }

            return(slnDir, slnFile, userOptsFile);
        }
Ejemplo n.º 50
0
 public ActiveSolutionTracker([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
 {
     this.solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
     Debug.Assert(this.solution != null, "Cannot find IVsSolution");
     ErrorHandler.ThrowOnFailure(this.solution.AdviseSolutionEvents(this, out this.cookie));
 }
Ejemplo n.º 51
0
        /// <summary>
        /// Initialize the nested hierarhy node.
        /// </summary>
        /// <param name="fileName">The file name of the nested project.</param>
        /// <param name="destination">The location of the nested project.</param>
        /// <param name="projectName">The name of the project.</param>
        /// <param name="createFlags">The nested project creation flags </param>
        /// <remarks>This methos should be called just after a NestedProjectNode object is created.</remarks>
        public virtual void Init(string fileName, string destination, string projectName, __VSCREATEPROJFLAGS createFlags)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "fileName");
            }

            if (String.IsNullOrEmpty(destination))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "destination");
            }

            this.projectName = Path.GetFileName(fileName);
            this.projectPath = Path.Combine(destination, this.projectName);

            // get the IVsSolution interface from the global service provider
            IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;

            Debug.Assert(solution != null, "Could not get the IVsSolution object from the services exposed by this project");
            if (solution == null)
            {
                throw new InvalidOperationException();
            }

            // Get the project type guid from project element
            string typeGuidString     = this.ItemNode.GetMetadataAndThrow(ProjectFileConstants.TypeGuid, new InvalidOperationException());
            Guid   projectFactoryGuid = Guid.Empty;

            if (!String.IsNullOrEmpty(typeGuidString))
            {
                projectFactoryGuid = new Guid(typeGuidString);
            }

            // Get the project factory.
            IVsProjectFactory projectFactory;

            ErrorHandler.ThrowOnFailure(solution.GetProjectFactory((uint)0, new Guid[] { projectFactoryGuid }, fileName, out projectFactory));

            this.CreateProjectDirectory();

            //Create new project using factory
            int    cancelled;
            Guid   refiid     = NativeMethods.IID_IUnknown;
            IntPtr projectPtr = IntPtr.Zero;

            // For a nested project the creation at unsafe location is governed by the parent project since the nested project will end up in the cone of the parent project.
            bool dontShowAgain = DontShowAgainDialog.ReadDontShowAgainValue(ProjectFactory.DontShowProjectSecurityWarningAgain);

            try
            {
                DontShowAgainDialog.WriteDontShowAgainValue(ProjectFactory.DontShowProjectSecurityWarningAgain, 1);
                ErrorHandler.ThrowOnFailure(projectFactory.CreateProject(fileName, destination, projectName, (uint)createFlags, ref refiid, out projectPtr, out cancelled));

                if (projectPtr != IntPtr.Zero)
                {
                    this.nestedHierarchy = Marshal.GetTypedObjectForIUnknown(projectPtr, typeof(IVsHierarchy)) as IVsHierarchy;
                    Debug.Assert(this.nestedHierarchy != null, "Nested hierarchy could not be created");
                    Debug.Assert(cancelled == 0);
                }
            }
            finally
            {
                if (projectPtr != IntPtr.Zero)
                {
                    // We created a new instance of the project, we need to call release to decrement the ref count
                    // the RCW (this.nestedHierarchy) still has a reference to it which will keep it alive
                    Marshal.Release(projectPtr);
                }

                // Revert back the old value that security questions about unsafe location are stil asked if that was the value.
                if (!dontShowAgain)
                {
                    DontShowAgainDialog.WriteDontShowAgainValue(ProjectFactory.DontShowProjectSecurityWarningAgain, 0);
                }
            }

            if (cancelled != 0 && this.nestedHierarchy == null)
            {
                ErrorHandler.ThrowOnFailure(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            // Link into the nested VS hierarchy.
            ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchy, this.ProjectMgr));
            ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchyItemid, (object)(int)this.ID));

            this.LockRDTEntry();

            this.ConnectPropertyNotifySink();
        }
Ejemplo n.º 52
0
 public BuildEventsWatcher(IVsSolution vsSolution, IVsSolutionBuildManager vsBuildManager)
 {
     _vsSolution     = vsSolution ?? throw new ArgumentNullException(nameof(vsSolution));
     _vsBuildManager = vsBuildManager ?? throw new ArgumentNullException(nameof(vsBuildManager));
 }
Ejemplo n.º 53
0
            public bool TrySelectFile(Project project, string title, string filter, string storageKey, out string file)
            {
                if (project == null)
                {
                    throw new ArgumentNullException("project");
                }

                IVsSolution solution = (IVsSolution)Dialog.ServiceProvider.GetService(typeof(SVsSolution));

                IVsHierarchy hierarchy;

                if (!NativeMethods.Succeeded(solution.GetProjectOfUniqueName(project.FullName, out hierarchy)))
                {
                    file = null;
                    return(false);
                }

                // We want to read/persist the last directory location that was used if a key is provided.
                string                  lastSelectedFile = null;
                ProjectSettings         settings         = null;
                IVsBuildPropertyStorage storage          = null;

                if (storageKey != null)
                {
                    storage = hierarchy as IVsBuildPropertyStorage;
                }

                if (storage != null)
                {
                    try
                    {
                        settings         = new ProjectSettings(storage);
                        lastSelectedFile = settings[storageKey];
                    }
                    catch
                    {
                        // We don't want to fail scaffolding/selection if we have a settings issue. We'll just
                        // ignore the settings entirely.
                        settings = null;
                    }
                }

                if (ProjectItemSelector.TrySelectItem(hierarchy, title, filter, lastSelectedFile, out file))
                {
                    if (settings != null)
                    {
                        try
                        {
                            settings[storageKey] = file;
                        }
                        catch
                        {
                            // We don't want to fail scaffolding/selection if we have a settings issue. We'll just
                            // ignore the settings entirely.
                            settings = null;
                        }
                    }

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        internal /* for testing */ static IDictionary <string, string> BuildProjectPathToIdMap(IVsSolution solution)
        {
            var map = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            // 1. Call with nulls to get the number of files
            const uint grfGetOpsIncludeUnloadedFiles = 0; // required since the projects might not have finished loading
            uint       fileCount;
            var        result = solution.GetProjectFilesInSolution(grfGetOpsIncludeUnloadedFiles, 0, null, out fileCount);

            if (ErrorHandler.Failed(result))
            {
                return(map);
            }

            // 2. Size array and call again to get the data
            string[] fileNames = new string[fileCount];
            result = solution.GetProjectFilesInSolution(grfGetOpsIncludeUnloadedFiles, fileCount, fileNames, out fileCount);
            if (ErrorHandler.Failed(result))
            {
                return(map);
            }

            IVsSolution5 soln5 = (IVsSolution5)solution;

            foreach (string projectFile in fileNames)
            {
                // We need to use the same project id that is used by the Scanner for MSBuild.
                // For non-.Net Core projects, the scanner will use the <ProjectGuid> value in the project.
                // .Net Core projects don't have a <ProjectGuid> property so the scanner uses the GUID allocated
                // to the project in the solution file.
                // Fortunately, this is the logic used by soln5.GetGuidOfProjectFile... so we can just use that.
                Guid projectGuid = soln5.GetGuidOfProjectFile(projectFile);

                // Overwrite duplicate entries. This won't happen for real project files: it will only happen
                // for solution folders with duplicate names, which we don't care about.
                map[projectFile] = projectGuid.ToString().Replace("{", "").Replace("}", "");
            }
            return(map);
        }
        /// <summary>
        /// Executes the action.
        /// </summary>
        public override void Execute()
        {
            // Skip action?
            if (IsMultiProjectSolution)
            {
                return;
            }

            DTE vs = this.GetService <DTE>(true);

            // Add a single project and add the necessary folders later
            string bsfTemplateLocation = @"Templates\Solutions\Projects\BizTalkApplication\BizTalkApplication.vstemplate";

            bsfTemplateLocation = BusinessComponents.Helper.GetBSFTemplateLocation() + bsfTemplateLocation;
            string projectToAddTemplateTo = BusinessComponents.Helper.GetProjectLocation(vs) + ProjectName;

            // Add the project to the solution and retrieve a reference (by default the returned project is null in this case)
            Project singleProject = null;

            vs.Solution.AddFromTemplate(bsfTemplateLocation, projectToAddTemplateTo, ProjectName, false);
            if (vs.Solution.Projects.Count == 1)
            {
                singleProject = vs.Solution.Projects.Item(1);
            }

            // Valid project reference found?
            if (singleProject != null)
            {
                // Add a binding folder
                singleProject.ProjectItems.AddFolder("Bindings", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);

                // Schemas folder wanted?
                if (AddSchemasFolder)
                {
                    singleProject.ProjectItems.AddFolder("Schemas", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                }
                // Maps folder wanted?
                if (AddMapsFolder)
                {
                    singleProject.ProjectItems.AddFolder("Maps", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                }
                // Orchestrations folder wanted?
                if (AddOrchestrationsFolder)
                {
                    singleProject.ProjectItems.AddFolder("Orchestrations", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                }
                // Pipelines folder wanted?
                if (AddPipelinesFolder)
                {
                    singleProject.ProjectItems.AddFolder("Pipelines", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                }
                // Business Components folder wanted?
                if (AddBusinessComponentsFolder)
                {
                    singleProject.ProjectItems.AddFolder("BusinessComponents", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                }
            }
            IVsSolution solution = (IVsSolution)GetService(typeof(SVsSolution));

            Helper.SetProjectProperty(solution, singleProject, "ApplicationName", BizTalkApplicationName, null, _PersistStorageType.PST_USER_FILE);
            Helper.SetProjectProperty(solution, singleProject, "Server", "localhost", null, _PersistStorageType.PST_USER_FILE);
            Helper.SetProjectProperty(solution, singleProject, "RestartHostInstances", "true", null, _PersistStorageType.PST_USER_FILE);
        }
Ejemplo n.º 56
0
        public int StartDeploy(IVsOutputWindowPane pIVsOutputWindowPane, uint dwOptions)
        {
            int continueOn = 1;

            outputWindow = pIVsOutputWindowPane;

            if (connection != null)
            {
                lock (syncObject) {
                    if (connection != null)
                    {
                        connection.Dispose();
                        connection = null;
                    }
                }
            }

            // Loop through deploy status callbacks
            foreach (IVsDeployStatusCallback callback in deployCallbackCollection)
            {
                if (ErrorHandler.Failed(callback.OnStartDeploy(ref continueOn)))
                {
                    continueOn = 0;
                }

                if (continueOn == 0)
                {
                    outputWindow = null;
                    return(VSConstants.E_ABORT);
                }
            }

            try {
                VsDebugTargetInfo2[] targets;
                uint   deployFlags          = (uint)(_AppContainerDeployOptions.ACDO_NetworkLoopbackEnable | _AppContainerDeployOptions.ACDO_SetNetworkLoopback);
                string recipeFile           = null;
                string layoutDir            = null;
                var    pythonProject        = PythonConfig;
                IVsBuildPropertyStorage bps = (IVsBuildPropertyStorage)pythonProject;
                int hr = QueryDebugTargets(out targets);
                if (ErrorHandler.Failed(hr))
                {
                    NotifyEndDeploy(0);
                    return(hr);
                }

                string canonicalName;

                get_CanonicalName(out canonicalName);

                bps.GetPropertyValue("AppxPackageRecipe", canonicalName, (uint)_PersistStorageType.PST_PROJECT_FILE, out recipeFile);

                string      projectUniqueName = null;
                IVsSolution vsSolution        = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
                if (vsSolution != null)
                {
                    hr = vsSolution.GetUniqueNameOfProject(pythonProject, out projectUniqueName);
                }

                IVsAppContainerProjectDeploy deployHelper = (IVsAppContainerProjectDeploy)Package.GetGlobalService(typeof(SVsAppContainerProjectDeploy));
                if (String.IsNullOrEmpty(targets[0].bstrRemoteMachine))
                {
                    bps.GetPropertyValue("LayoutDir", canonicalName, (uint)_PersistStorageType.PST_PROJECT_FILE, out layoutDir);

                    deployOp = deployHelper.StartDeployAsync(deployFlags, recipeFile, layoutDir, projectUniqueName, this);
                }
                else
                {
                    IVsDebuggerDeploy           deploy = (IVsDebuggerDeploy)Package.GetGlobalService(typeof(SVsShellDebugger));
                    IVsDebuggerDeployConnection deployConnection;

                    hr = deploy.ConnectToTargetComputer(targets[0].bstrRemoteMachine, VsDebugRemoteAuthenticationMode.VSAUTHMODE_None, out deployConnection);
                    if (ErrorHandler.Failed(hr))
                    {
                        NotifyEndDeploy(0);
                        return(hr);
                    }

                    connection = deployConnection;

                    deployOp = deployHelper.StartRemoteDeployAsync(deployFlags, connection, recipeFile, projectUniqueName, this);
                }
            } catch (Exception) {
                if (connection != null)
                {
                    lock (syncObject) {
                        if (connection != null)
                        {
                            connection.Dispose();
                            connection = null;
                        }
                    }
                }
                connection = null;

                NotifyEndDeploy(0);

                // Rethrow exception
                throw;
            }

            return(VSConstants.S_OK);
        }
 private DeleteOutputArtifacts(System.IServiceProvider serviceProvider, IVsSolution solution, DTE2 dte)
 {
     _serviceProvider = serviceProvider;
     _solution        = solution;
     _dte             = dte;
 }
Ejemplo n.º 58
0
 internal static IEnumerable <PythonProjectNode> EnumerateLoadedPythonProjects(this IVsSolution solution)
 {
     return(EnumerateLoadedProjects(solution)
            .Select(p => p.GetPythonProject())
            .Where(p => p != null));
 }
Ejemplo n.º 59
0
        // returns a valid Guid if the project was reloaded or an empty Guid if the project did not need to be reloaded
        static public Guid ReloadProject(Project project)
        {
            Logging.Logging.LogInfo("Attempting to reload project");

            try
            {
                if (project != null && project.Kind == EnvDTE.Constants.vsProjectKindUnmodeled)
                {
                    DTE dte = project.DTE;

                    ServiceProvider sp         = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
                    IVsSolution     vsSolution = sp.GetService(typeof(IVsSolution)) as IVsSolution;

                    IVsHierarchy hierarchy;

                    string solutionDirectory = "";
                    string solutionFile      = "";
                    string userOptions       = "";
                    vsSolution.GetSolutionInfo(out solutionDirectory, out solutionFile, out userOptions);

                    vsSolution.GetProjectOfUniqueName(solutionDirectory + project.UniqueName, out hierarchy);

                    if (hierarchy != null)
                    {
                        Guid projectGuid;

                        hierarchy.GetGuidProperty(
                            VSConstants.VSITEMID_ROOT,
                            (int)__VSHPROPID.VSHPROPID_ProjectIDGuid,
                            out projectGuid);

                        if (projectGuid != null)
                        {
                            Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' with GUID {" + projectGuid.ToString() + "} loaded.");
                            (vsSolution as IVsSolution4).ReloadProject(projectGuid);
                            return(projectGuid);
                        }
                        else
                        {
                            Logging.Logging.LogError("Failed to load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
                        }
                    }
                    else
                    {
                        Logging.Logging.LogError("Failed to retrieve IVsHierarchy. Can't load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
                    }
                }
                else
                {
                    if (project == null)
                    {
                        Logging.Logging.LogWarning("Project is null");
                    }
                    else
                    {
                        Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' is already loaded");
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Logging.LogError("Exception: " + e.Message);

                return(Guid.Empty);
            }

            return(Guid.Empty);
        }
Ejemplo n.º 60
-1
		public static void AddSolutionItem(IVsSolution solution, string fileName)
		{
			uint itemId = DteHelper2.FindItemByName(
				solution as IVsHierarchy, "Solution Items");

			IntPtr ptr = IntPtr.Zero;
			Guid solutionFolderGuid = new Guid("2150E333-8FDC-42a3-9474-1A3956D46DE8");
			Guid iidProject = typeof(IVsHierarchy).GUID;

			int res = solution.CreateProject(
				ref solutionFolderGuid,
				null,
				null,
				"Solution Items",
				0,
				ref iidProject,
				out ptr);

			if(ptr != IntPtr.Zero)
			{
				IVsHierarchy hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(ptr);

				Guid projGuid;

				hierarchy.GetGuidProperty(
					VSConstants.VSITEMID_ROOT,
					(int)__VSHPROPID.VSHPROPID_ProjectIDGuid,
					out projGuid);

				ProjectNode node = new ProjectNode(solution, projGuid);

				node.AddItem(fileName);
			}
		}