コード例 #1
0
ファイル: NodejsFileNode.cs プロジェクト: lioaphy/nodejstools
        // TODO: Need to update analysis for files changed outside of VS
        private void CreateWatcher(string filename)
        {
#if FALSE
            if (CommonUtils.IsSubpathOf(ProjectMgr.ProjectHome, filename))
            {
                // we want to subscribe to the project's file system watcher so users
                // can continue to rename the directory which contains this file.
                ProjectMgr.RegisterFileChangeNotification(this, FileContentsChanged);
            }
            else
            {
                // this is a link file which lives outside of our project directory,
                // we'll need to watch the file directly, which means we're going to
                // prevent it's parent directory from being renamed.
                _watcher = new FileSystemWatcher(Path.GetDirectoryName(filename), Path.GetFileName(filename));
                _watcher.EnableRaisingEvents = true;
                _watcher.Changed            += FileContentsChanged;
                _watcher.Renamed            += FileContentsChanged;
                _watcher.NotifyFilter        = NotifyFilters.LastWrite;
            }
#endif
        }
コード例 #2
0
        /// <summary>
        /// Handles the exclude from project command.
        /// </summary>
        /// <returns></returns>
        internal override int ExcludeFromProject()
        {
            Debug.Assert(this.ProjectMgr != null, "The project item " + this.ToString() + " has not been initialised correctly. It has a null ProjectMgr");
            if (!ProjectMgr.QueryEditProjectFile(false) ||
                !ProjectMgr.QueryFolderRemove(Parent, Url))
            {
                return(VSConstants.E_FAIL);
            }

            for (var child = FirstChild; child != null; child = child.NextSibling)
            {
                // we automatically exclude all children below us too
                int hr = child.ExcludeFromProject();
                if (ErrorHandler.Failed(hr))
                {
                    return(hr);
                }
            }

            ResetNodeProperties();
            ItemNode.RemoveFromProjectFile();
            if (!Directory.Exists(CommonUtils.TrimEndSeparator(Url)))
            {
                Parent.RemoveChild(this);
                ProjectMgr.OnItemDeleted(this);
            }
            else
            {
                ItemNode = new AllFilesProjectElement(Url, ItemNode.ItemTypeName, ProjectMgr);
                if (!ProjectMgr.IsShowingAllFiles)
                {
                    IsVisible = false;
                    ProjectMgr.OnInvalidateItems(Parent);
                }
                ProjectMgr.ReDrawNode(this, UIHierarchyElement.Icon);
                ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, 0);
            }
            return(VSConstants.S_OK);
        }
コード例 #3
0
ファイル: ProjectSettingsPage.cs プロジェクト: formist/LinkMe
        protected override void BindProperties()
        {
            if (ProjectMgr == null)
            {
                return;
            }

            m_outputName = ProjectMgr.GetProjectProperty("OutputName", true);
            string generateConfigurationFile = ProjectMgr.GetProjectProperty("GenerateConfigurationFile", true);

            m_generateConfigurationFile = generateConfigurationFile == null || generateConfigurationFile == string.Empty ? false : bool.Parse(generateConfigurationFile);
            string generateAssembly = ProjectMgr.GetProjectProperty("GenerateAssembly", true);

            m_generateAssembly = generateAssembly == null || generateAssembly == string.Empty ? false : bool.Parse(generateAssembly);
            string keyFile = ProjectMgr.GetProjectProperty("KeyFile", true);

            if (!string.IsNullOrEmpty(keyFile))
            {
                m_keyFile = FileSystem.GetAbsolutePath(keyFile, ProjectMgr.BaseURI.Directory);
            }
            m_version = ProjectMgr.GetProjectProperty("Version", true);
        }
コード例 #4
0
ファイル: NodejsFileNode.cs プロジェクト: ipaste/nodejstools
        internal override int IncludeInProject(bool includeChildren)
        {
            if (!ItemNode.IsExcluded)
            {
                return(0);
            }

            // Check if parent folder is designated as containing client-side code.
            var isContent  = false;
            var folderNode = this.Parent as NodejsFolderNode;

            if (folderNode != null)
            {
                var contentType = folderNode.ContentType;
                switch (contentType)
                {
                case FolderContentType.Browser:
                    isContent = true;
                    break;
                }
            }

            var includeInProject = base.IncludeInProject(includeChildren);

            if (isContent && Url.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
            {
                this.ItemNode.ItemTypeName = ProjectFileConstants.Content;
            }

            if (ProjectMgr.ShouldAcquireTypingsAutomatically)
            {
                ProjectMgr.Site.GetUIThread().Invoke(() => {
                    ProjectMgr.OnItemAdded(this.Parent, this);
                });
            }

            return(includeInProject);
        }
コード例 #5
0
        public override int QueryService(ref Guid guidService, out object result)
        {
            var model           = ProjectMgr.GetService(typeof(SComponentModel)) as IComponentModel;
            var designerSupport = model?.GetService <IXamlDesignerSupport>();

            if (designerSupport != null &&
                guidService == designerSupport.DesignerContextTypeGuid &&
                Path.GetExtension(Url).Equals(".xaml", StringComparison.OrdinalIgnoreCase))
            {
                // Create a DesignerContext for the XAML designer for this file
                if (_designerContext == null)
                {
                    _designerContext = designerSupport.CreateDesignerContext();
                    var child = (
                        // look for spam.py
                        ProjectMgr.FindNodeByFullPath(Path.ChangeExtension(Url, PythonConstants.FileExtension)) ??
                        // then look for spam.pyw
                        ProjectMgr.FindNodeByFullPath(Path.ChangeExtension(Url, PythonConstants.WindowsFileExtension))
                        ) as CommonFileNode;

                    if (child != null)
                    {
                        PythonFileNode pythonNode = child as PythonFileNode;
                        if (pythonNode != null)
                        {
                            designerSupport.InitializeEventBindingProvider(
                                _designerContext,
                                new XamlCallback(pythonNode)
                                );
                        }
                    }
                }
                result = _designerContext;
                return(VSConstants.S_OK);
            }

            return(base.QueryService(ref guidService, out result));
        }
コード例 #6
0
ファイル: ProjectTree.cs プロジェクト: radtek/Tools
        internal void InitProjTree(ProjectMgr projMgr)
        {
            _projMgr = projMgr;

            // Projects
            TreeNode root = AddNode(projMgr, "Projects", null);

            foreach (var proj in projMgr.ProjList)
            {
                TreeNode projNode       = AddNode(proj, proj.Name, root);
                TreeNode displayMgrNode = AddNode(proj.DisplayMgr, "Displays", projNode);
                displayMgrNode.ContextMenuStrip = _menuProj;

                foreach (var group in proj.DisplayMgr.GroupList)
                {
                    if (group.ParentGroup == null)
                    {
                        TreeNode groupNode = AddNode(group, group.Name, displayMgrNode);
                        groupNode.ContextMenuStrip = _menuGroup;
                        InitGroupTree(group, groupNode);
                    }
                }
                foreach (var display in proj.DisplayMgr.DisplayList)
                {
                    if (display.Group == null)
                    {
                        TreeNode dispNode = AddNode(display, display.Name, displayMgrNode);
                        dispNode.ContextMenuStrip = _menuDisplay;
                    }
                    else
                    {
                        TreeNode dispNode = AddNode(display, display.Name, display.Group);
                        dispNode.ContextMenuStrip = _menuDisplay;
                    }
                }
            }
            root.ExpandAll();
        }
コード例 #7
0
        public override object GetIconHandle(bool open)
        {
            if (ProjectMgr == null)
            {
                return(null);
            }

            int index;

            if (!_interpreters.IsAvailable(_factory))
            {
                index = ProjectMgr.GetIconIndex(PythonProjectImageName.MissingInterpreter);
            }
            else if (_interpreters.ActiveInterpreter == _factory)
            {
                index = ProjectMgr.GetIconIndex(PythonProjectImageName.ActiveInterpreter);
            }
            else
            {
                index = ProjectMgr.GetIconIndex(PythonProjectImageName.Interpreter);
            }
            return(this.ProjectMgr.ImageHandler.GetIconHandle(index));
        }
コード例 #8
0
ファイル: Application.cs プロジェクト: watsug/Boo-Plugin
        /// <summary>
        /// Apply Changes on project node.
        /// </summary>
        /// <returns>E_INVALIDARG if internal ProjectMgr is null, otherwise applies changes and return S_OK.</returns>
        protected override int ApplyChanges()
        {
            if (ProjectMgr == null)
            {
                return(VSConstants.E_INVALIDARG);
            }

            var  propertyPageFrame = (IVsPropertyPageFrame)ProjectMgr.Site.GetService((typeof(SVsPropertyPageFrame)));
            bool reloadRequired    = ProjectMgr.TargetFrameworkMoniker != targetFrameworkMoniker;

            ProjectMgr.SetProjectProperty("AssemblyName", assemblyName);
            ProjectMgr.SetProjectProperty("OutputType", outputType.ToString());
            ProjectMgr.SetProjectProperty("RootNamespace", defaultNamespace);
            ProjectMgr.SetProjectProperty("StartupObject", startupObject);
            ProjectMgr.SetProjectProperty("ApplicationIcon", applicationIcon);
            ProjectMgr.SetProjectProperty("AllowUnsafeBlocks", allowUnsafe.ToString());
            ProjectMgr.SetProjectProperty("Ducky", useDuckTyping.ToString());

            if (reloadRequired)
            {
                if (MessageBox.Show(SR.GetString(SR.ReloadPromptOnTargetFxChanged), SR.GetString(SR.ReloadPromptOnTargetFxChangedCaption), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    ProjectMgr.TargetFrameworkMoniker = targetFrameworkMoniker;
                }
            }

            IsDirty = false;

            if (reloadRequired)
            {
                // This prevents the property page from displaying bad data from the zombied (unloaded) project
                propertyPageFrame.HideFrame();
                propertyPageFrame.ShowFrame(GetType().GUID);
            }

            return(VSConstants.S_OK);
        }
コード例 #9
0
        internal override int ExecCommandOnNode(Guid guidCmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            Debug.Assert(this.ProjectMgr != null, "The Dynamic FileNode has no project manager");
            Utilities.CheckNotNull(this.ProjectMgr);

            if (guidCmdGroup == GuidList.guidPythonToolsCmdSet)
            {
                switch (cmd)
                {
                case CommonConstants.SetAsStartupFileCmdId:
                    // Set the StartupFile project property to the Url of this node
                    ProjectMgr.SetProjectProperty(
                        CommonConstants.StartupFile,
                        PathUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, Url)
                        );
                    return(VSConstants.S_OK);

                case CommonConstants.StartDebuggingCmdId:
                case CommonConstants.StartWithoutDebuggingCmdId:
                    IProjectLauncher starter = ((CommonProjectNode)ProjectMgr).GetLauncher();
                    if (starter != null)
                    {
                        if (!Utilities.SaveDirtyFiles())
                        {
                            // Abort
                            return(VSConstants.E_ABORT);
                        }

                        starter.LaunchFile(this.Url, cmd == CommonConstants.StartDebuggingCmdId);
                    }
                    return(VSConstants.S_OK);
                }
            }

            return(base.ExecCommandOnNode(guidCmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut));
        }
コード例 #10
0
ファイル: Application.cs プロジェクト: watsug/Boo-Plugin
        /// <summary>
        /// Bind properties.
        /// </summary>
        protected override void BindProperties()
        {
            if (ProjectMgr == null)
            {
                return;
            }

            assemblyName = ProjectMgr.GetProjectProperty("AssemblyName", true);

            var temp = ProjectMgr.GetProjectProperty("OutputType", false);

            if (!string.IsNullOrEmpty(temp))
            {
                try
                {
                    outputType = (OutputType)Enum.Parse(typeof(OutputType), temp);
                }
                catch (ArgumentException)
                {
                }
            }

            defaultNamespace = ProjectMgr.GetProjectProperty("RootNamespace", false);
            startupObject    = ProjectMgr.GetProjectProperty("StartupObject", false);
            applicationIcon  = ProjectMgr.GetProjectProperty("ApplicationIcon", false);
            Boolean.TryParse(ProjectMgr.GetProjectProperty("AllowUnsafeBlocks", false), out allowUnsafe);
            Boolean.TryParse(ProjectMgr.GetProjectProperty("Ducky", false), out useDuckTyping);

            try
            {
                targetFrameworkMoniker = ProjectMgr.TargetFrameworkMoniker;
            }
            catch (ArgumentException)
            {
            }
        }
コード例 #11
0
ファイル: FileNode.cs プロジェクト: DavidFeng/BabeLua
        /// <summary>
        /// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
        /// </summary>
        /// <param name="oldFileName">The old file name.</param>
        /// <param name="newFileName">The new file name</param>
        /// <param name="newParentId">The new parent id of the item.</param>
        /// <returns>The newly added FileNode.</returns>
        /// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
        private FileNode RenameFileNode(string oldFileName, string newFileName, HierarchyNode newParent)
        {
            if (CommonUtils.IsSamePath(oldFileName, newFileName))
            {
                // We do not want to rename the same file
                return(null);
            }

            if (newParent.IsNonMemberItem)
            {
                ErrorHandler.ThrowOnFailure(newParent.IncludeInProject(false));
            }
            using (this.ProjectMgr.ExtensibilityEventsDispatcher.Suspend()) {
                ProjectMgr.OnItemDeleted(this);
                this.Parent.RemoveChild(this);
                this.ID = this.ProjectMgr.ItemIdMap.Add(this);
                this.ItemNode.Rename(CommonUtils.GetRelativeFilePath(ProjectMgr.ProjectHome, newFileName));
                this.ItemNode.RefreshProperties();
                newParent.AddChild(this);
                this.Parent = newParent;
            }

            ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption);

            this.ProjectMgr.ExtensibilityEventsDispatcher.FireItemRenamed(this, Path.GetFileName(newFileName));

            //Update the new document in the RDT.
            DocumentManager.RenameDocument(this.ProjectMgr.Site, oldFileName, newFileName, ID);

            //Select the new node in the hierarchy
            ExpandItem(EXPANDFLAGS.EXPF_SelectItem);

            RenameChildNodes(this);

            return(this);
        }
コード例 #12
0
ファイル: ProjectConfig.cs プロジェクト: rkhjjs/VSGenero
        internal ProjectConfig(ProjectNode project, string configuration)
        {
            this.project = project;

            if (configuration.Contains("|"))
            { // If configuration is in the form "<Configuration>|<Platform>"
                string[] configStrArray = configuration.Split('|');
                if (2 == configStrArray.Length)
                {
                    this.configName   = configStrArray[0];
                    this.platformName = configStrArray[1];
                }
                else
                {
                    throw new Exception(string.Format(CultureInfo.InvariantCulture, "Invalid configuration format: {0}", configuration));
                }
            }
            else
            { // If configuration is in the form "<Configuration>"
                this.configName = configuration;
            }

            var flavoredCfgProvider = ProjectMgr.GetOuterInterface <IVsProjectFlavorCfgProvider>();

            Utilities.ArgumentNotNull("flavoredCfgProvider", flavoredCfgProvider);
            ErrorHandler.ThrowOnFailure(flavoredCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
            Utilities.ArgumentNotNull("flavoredCfg", flavoredCfg);

            // if the flavored object support XML fragment, initialize it
            IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;

            if (null != persistXML)
            {
                this.project.LoadXmlFragment(persistXML, configName, platformName);
            }
        }
コード例 #13
0
ファイル: FileNode.cs プロジェクト: DavidFeng/BabeLua
        /// <summary>
        /// Renames the file node for a case only change.
        /// </summary>
        /// <param name="newFileName">The new file name.</param>
        private void RenameCaseOnlyChange(string oldName, string newName)
        {
            //Update the include for this item.
            string relName = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, newName);

            Debug.Assert(String.Equals(this.ItemNode.GetMetadata(ProjectFileConstants.Include), relName, StringComparison.OrdinalIgnoreCase),
                         "Not just changing the filename case");

            this.ItemNode.Rename(relName);
            this.ItemNode.RefreshProperties();

            ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption);
            this.RenameChildNodes(this);

            // Refresh the property browser.
            IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;

            Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");

            ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));

            //Select the new node in the hierarchy
            ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
        }
コード例 #14
0
        private int FinishFolderAdd(string label, bool wasCancelled)
        {
            // finish creation
            string filename = label.Trim();

            if (filename == "." || filename == "..")
            {
                Debug.Assert(!wasCancelled);   // cancelling leaves us with a valid label
                NativeMethods.SetErrorDescription("{0} is an invalid filename.", filename);
                return(VSConstants.E_FAIL);
            }

            var path = Path.Combine(Parent.FullPathToChildren, label);

            if (path.Length >= NativeMethods.MAX_FOLDER_PATH)
            {
                if (wasCancelled)
                {
                    // cancelling an edit label doesn't result in the error
                    // being displayed, so we'll display one for the user.
                    VsShellUtilities.ShowMessageBox(
                        ProjectMgr.Site,
                        null,
                        PathTooLongMessage,
                        OLEMSGICON.OLEMSGICON_CRITICAL,
                        OLEMSGBUTTON.OLEMSGBUTTON_OK,
                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
                        );
                }
                else
                {
                    NativeMethods.SetErrorDescription(PathTooLongMessage);
                }
                return(VSConstants.E_FAIL);
            }

            if (filename == Caption || Parent.FindImmediateChildByName(filename) == null)
            {
                if (ProjectMgr.QueryFolderAdd(Parent, path))
                {
                    Directory.CreateDirectory(path);
                    IsBeingCreated = false;
                    var relativePath = CommonUtils.GetRelativeDirectoryPath(
                        ProjectMgr.ProjectHome,
                        Path.Combine(Path.GetDirectoryName(CommonUtils.TrimEndSeparator(Url)), label));
                    this.ItemNode.Rename(relativePath);

                    ProjectMgr.OnItemDeleted(this);
                    this.Parent.RemoveChild(this);
                    this.ID = ProjectMgr.ItemIdMap.Add(this);
                    this.Parent.AddChild(this);

                    ExpandItem(EXPANDFLAGS.EXPF_SelectItem);

                    ProjectMgr.Tracker.OnFolderAdded(
                        path,
                        VSADDDIRECTORYFLAGS.VSADDDIRECTORYFLAGS_NoFlags
                        );
                }
            }
            else
            {
                Debug.Assert(!wasCancelled);    // we choose a label which didn't exist when we started the edit
                // Set error: folder already exists
                NativeMethods.SetErrorDescription("The folder {0} already exists.", filename);
                return(VSConstants.E_FAIL);
            }
            return(VSConstants.S_OK);
        }
コード例 #15
0
        /// <summary>
        /// Rename Folder
        /// </summary>
        /// <param name="label">new Name of Folder</param>
        /// <returns>VSConstants.S_OK, if succeeded</returns>
        public override int SetEditLabel(string label)
        {
            if (IsBeingCreated)
            {
                return(FinishFolderAdd(label, false));
            }
            else
            {
                if (String.Equals(Path.GetFileName(CommonUtils.TrimEndSeparator(this.Url)), label, StringComparison.Ordinal))
                {
                    // Label matches current Name
                    return(VSConstants.S_OK);
                }

                string newPath = CommonUtils.NormalizeDirectoryPath(Path.Combine(
                                                                        Path.GetDirectoryName(CommonUtils.TrimEndSeparator(this.Url)), label));

                // Verify that No Directory/file already exists with the new name among current children
                var existingChild = Parent.FindImmediateChildByName(label);
                if (existingChild != null && existingChild != this)
                {
                    return(ShowFileOrFolderAlreadyExistsErrorMessage(newPath));
                }

                // Verify that No Directory/file already exists with the new name on disk
                if (Directory.Exists(newPath) || File.Exists(newPath))
                {
                    return(ShowFileOrFolderAlreadyExistsErrorMessage(newPath));
                }

                if (!ProjectMgr.Tracker.CanRenameItem(Url, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_Directory))
                {
                    return(VSConstants.S_OK);
                }
            }

            try
            {
                var oldTriggerFlag = this.ProjectMgr.EventTriggeringFlag;
                ProjectMgr.EventTriggeringFlag |= ProjectNode.EventTriggering.DoNotTriggerTrackerQueryEvents;
                try
                {
                    RenameFolder(label);
                }
                finally
                {
                    ProjectMgr.EventTriggeringFlag = oldTriggerFlag;
                }


                //Refresh the properties in the properties window
                IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell;
                Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
                ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));

                // Notify the listeners that the name of this folder is changed. This will
                // also force a refresh of the SolutionExplorer's node.
                ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.RenameFolder, CultureInfo.CurrentUICulture), e.Message));
            }
            return(VSConstants.S_OK);
        }
コード例 #16
0
ファイル: ReferenceNode.cs プロジェクト: shijiong/ntvsiot
 /// <summary>
 /// Refreshes a reference by re-resolving it and redrawing the icon.
 /// </summary>
 internal virtual void RefreshReference()
 {
     this.ResolveReference();
     ProjectMgr.ReDrawNode(this, UIHierarchyElement.Icon);
 }
コード例 #17
0
ファイル: FileNode.cs プロジェクト: rkhjjs/VSGenero
        /// <summary>
        /// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
        /// </summary>
        /// <param name="docData">A pointer to the document in the rdt</param>
        /// <param name="newFilePath">The new file path to the document</param>
        /// <returns></returns>
        internal override int AfterSaveItemAs(IntPtr docData, string newFilePath)
        {
            Utilities.ArgumentNotNullOrEmpty("newFilePath", newFilePath);

            int returnCode = VSConstants.S_OK;

            newFilePath = newFilePath.Trim();

            //Identify if Path or FileName are the same for old and new file
            string newDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(newFilePath));
            string oldDirectoryName = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.GetMkDocument()));
            bool   isSamePath       = CommonUtils.IsSameDirectory(newDirectoryName, oldDirectoryName);
            bool   isSameFile       = CommonUtils.IsSamePath(newFilePath, this.Url);

            //Get target container
            HierarchyNode targetContainer = null;
            bool          isLink          = false;

            if (isSamePath)
            {
                targetContainer = this.Parent;
            }
            else if (!CommonUtils.IsSubpathOf(this.ProjectMgr.ProjectHome, newDirectoryName))
            {
                targetContainer = this.Parent;
                isLink          = true;
            }
            else if (CommonUtils.IsSameDirectory(this.ProjectMgr.ProjectHome, newDirectoryName))
            {
                //the projectnode is the target container
                targetContainer = this.ProjectMgr;
            }
            else
            {
                //search for the target container among existing child nodes
                targetContainer = this.ProjectMgr.FindNodeByFullPath(newDirectoryName);
                if (targetContainer != null && (targetContainer is FileNode))
                {
                    // We already have a file node with this name in the hierarchy.
                    throw new InvalidOperationException(SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, Path.GetFileName(newFilePath)));
                }
            }

            if (targetContainer == null)
            {
                // Add a chain of subdirectories to the project.
                string relativeUri = CommonUtils.GetRelativeDirectoryPath(this.ProjectMgr.ProjectHome, newDirectoryName);
                targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
            }
            Utilities.CheckNotNull(targetContainer, "Could not find a target container");

            //Suspend file changes while we rename the document
            string             oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
            string             oldName    = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, oldrelPath);
            SuspendFileChanges sfc        = new SuspendFileChanges(this.ProjectMgr.Site, oldName);

            sfc.Suspend();

            try
            {
                // Rename the node.
                DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
                // Check if the file name was actually changed.
                // In same cases (e.g. if the item is a file and the user has changed its encoding) this function
                // is called even if there is no real rename.
                if (!isSameFile || (this.Parent.ID != targetContainer.ID))
                {
                    // The path of the file is changed or its parent is changed; in both cases we have
                    // to rename the item.
                    if (isLink != IsLinkFile)
                    {
                        if (isLink)
                        {
                            var newPath = CommonUtils.GetRelativeFilePath(
                                this.ProjectMgr.ProjectHome,
                                Path.Combine(Path.GetDirectoryName(Url), Path.GetFileName(newFilePath))
                                );

                            ItemNode.SetMetadata(ProjectFileConstants.Link, newPath);
                        }
                        else
                        {
                            ItemNode.SetMetadata(ProjectFileConstants.Link, null);
                        }
                        SetIsLinkFile(isLink);
                    }

                    RenameFileNode(oldName, newFilePath, targetContainer);
                    ProjectMgr.OnInvalidateItems(this.Parent);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception : " + e.Message);
                this.RecoverFromRenameFailure(newFilePath, oldrelPath);
                throw;
            }
            finally
            {
                sfc.Resume();
            }

            return(returnCode);
        }
コード例 #18
0
ファイル: FileNode.cs プロジェクト: rkhjjs/VSGenero
        /// <summary>
        /// Rename the underlying document based on the change the user just made to the edit label.
        /// </summary>
        protected internal override int SetEditLabel(string label, string relativePath)
        {
            int    returnValue = VSConstants.S_OK;
            uint   oldId       = this.ID;
            string strSavePath = Path.GetDirectoryName(relativePath);

            strSavePath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectMgr.ProjectHome, strSavePath);
            string newName = Path.Combine(strSavePath, label);

            if (String.Equals(newName, this.Url, StringComparison.Ordinal))
            {
                // This is really a no-op (including changing case), so there is nothing to do
                return(VSConstants.S_FALSE);
            }
            else if (String.Equals(newName, this.Url, StringComparison.OrdinalIgnoreCase))
            {
                // This is a change of file casing only.
            }
            else
            {
                // If the renamed file already exists then quit (unless it is the result of the parent having done the move).
                if (IsFileOnDisk(newName) &&
                    (IsFileOnDisk(this.Url) ||
                     !String.Equals(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.OrdinalIgnoreCase)))
                {
                    throw new InvalidOperationException(SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, label));
                }
                else if (newName.Length > NativeMethods.MAX_PATH)
                {
                    throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
                }
            }

            string oldName = this.Url;
            // must update the caption prior to calling RenameDocument, since it may
            // cause queries of that property (such as from open editors).
            string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);

            try
            {
                if (!RenameDocument(oldName, newName))
                {
                    this.ItemNode.Rename(oldrelPath);
                }

                if (this is DependentFileNode)
                {
                    ProjectMgr.OnInvalidateItems(this.Parent);
                }
            }
            catch (Exception e)
            {
                // Just re-throw the exception so we don't get duplicate message boxes.
                Trace.WriteLine("Exception : " + e.Message);
                this.RecoverFromRenameFailure(newName, oldrelPath);
                returnValue = Marshal.GetHRForException(e);
                throw;
            }
            // Return S_FALSE if the hierarchy item id has changed.  This forces VS to flush the stale
            // hierarchy item id.
            if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED)
            {
                return((oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE);
            }

            return(returnValue);
        }
コード例 #19
0
 private void EventListener_BuildCompleted(object sender, EventArgs e)
 {
     InitializeFileChangeListener();
     AddAnalyzedAssembly(((PythonProjectNode)ProjectMgr).GetAnalyzer()).DoNotWait();
     ProjectMgr.OnInvalidateItems(Parent);
 }
コード例 #20
0
ファイル: InterpretersNode.cs プロジェクト: PeezoSlug/PTVS
        private async Task RefreshPackagesAsync(IPackageManager packageManager)
        {
            if (_suppressPackageRefresh || packageManager == null)
            {
                return;
            }

            bool prevChecked = _checkedItems;

            // Use _checkingItems to prevent the expanded state from
            // disappearing too quickly.
            _checkingItems = true;
            _checkedItems  = true;

            var packages = new Dictionary <string, PackageSpec>();

            foreach (var p in await packageManager.GetInstalledPackagesAsync(CancellationToken.None))
            {
                packages[p.FullSpec] = p;
            }

            await ProjectMgr.Site.GetUIThread().InvokeAsync(() => {
                if (ProjectMgr == null || ProjectMgr.IsClosed)
                {
                    return;
                }

                try {
                    var logger = ProjectMgr.Site.GetPythonToolsService().Logger;
                    if (logger != null)
                    {
                        foreach (var p in packages)
                        {
                            logger.LogEvent(PythonLogEvent.PythonPackage,
                                            new PackageInfo {
                                Name = p.Value.Name.ToLowerInvariant()
                            });
                        }
                    }
                } catch (Exception ex) {
                    Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
                }

                bool anyChanges = false;
                var existing    = AllChildren.OfType <InterpretersPackageNode>().ToDictionary(c => c.Url);

                // remove the nodes which were uninstalled.
                foreach (var keyValue in existing)
                {
                    if (!packages.Remove(keyValue.Key))
                    {
                        RemoveChild(keyValue.Value);
                        anyChanges = true;
                    }
                }

                // add the new nodes
                foreach (var p in packages.OrderBy(kv => kv.Key))
                {
                    AddChild(new InterpretersPackageNode(ProjectMgr, p.Value));
                    anyChanges = true;
                }
                _checkingItems = false;

                ProjectMgr.OnInvalidateItems(this);
                if (!prevChecked)
                {
                    if (anyChanges)
                    {
                        ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Expandable, 0);
                    }
                    if (ProjectMgr.ParentHierarchy != null)
                    {
                        ExpandItem(EXPANDFLAGS.EXPF_CollapseFolder);
                    }
                }
            });
        }
コード例 #21
0
 public sealed override object GetIconHandle(bool open)
 {
     //We don't want the icon to become an expanded folder 'OpenReferenceFolder'
     //  Thus we always return 'ReferenceFolder'
     return(ProjectMgr.GetIconHandleByName(ProjectNode.ImageName.ReferenceFolder));
 }
コード例 #22
0
ファイル: NemerleFileNode.cs プロジェクト: ugurak/nemerle
        int IProjectSourceNode.ExcludeFromProject()
        {
            if (ProjectMgr == null || ProjectMgr.IsClosed)
            {
                return((int)OleConstants.OLECMDERR_E_NOTSUPPORTED);
            }

            if (IsNonMemberItem)
            {
                return(VSConstants.S_OK);                // do nothing, just ignore it.
            }
            ((NemerlePackage)ProjectMgr.Package).SetWaitCursor();
            // Ask Document tracker listeners if we can remove the item.
            {             // just to limit the scope.
                string   documentToRemove = GetMkDocument();
                string[] filesToBeDeleted = new[] { documentToRemove };
                VSQUERYREMOVEFILEFLAGS[] queryRemoveFlags = GetQueryRemoveFileFlags(filesToBeDeleted);
                if (!ProjectMgr.Tracker.CanRemoveItems(filesToBeDeleted, queryRemoveFlags))
                {
                    return((int)OleConstants.OLECMDERR_E_CANCELED);
                }

                // Close the document if it has a manager.
                DocumentManager manager = GetDocumentManager();
                if (manager != null)
                {
                    if (manager.Close(__FRAMECLOSE.FRAMECLOSE_PromptSave) == VSConstants.E_ABORT)
                    {
                        return(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                    }
                }

                if (!ProjectMgr.QueryEditProjectFile(false))
                {
                    throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                }
            }

            // close the document window if open.
            CloseDocumentWindow(this);

            NemerleProjectNode projectNode = ProjectMgr as NemerleProjectNode;

            if (projectNode != null && projectNode.ShowAllFilesEnabled && File.Exists(Url))
            {
                string url = Url;                 // need to store before removing the node.
                ItemNode.RemoveFromProjectFile();
                ProjectMgr.Tracker.OnItemRemoved(url, VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_NoFlags);
                SetProperty((int)__VSHPROPID.VSHPROPID_IsNonMemberItem, true);         // Set it as non member item
                ItemNode = new ProjectElement(ProjectMgr, null, true);                 // now we have to set a new ItemNode to indicate that this is virtual node.
                ItemNode.Rename(url);
                ItemNode.SetMetadata(ProjectFileConstants.Name, url);

                //ProjectMgr.OnItemDeleted();
                var proj = ProjectInfo.FindProject(ProjectMgr);
                if (proj != null)
                {
                    proj.RemoveSource(this.Url);
                }

                ReDraw(UIHierarchyElement.Icon);     // We have to redraw the icon of the node as it is now not a member of the project and should be drawn using a different icon.
                ReDraw(UIHierarchyElement.SccState); // update the SCC state icon.
            }
            else if (Parent != null)                 // the project node has no parentNode
            {
                // Remove from the Hierarchy
                OnItemDeleted();
                Parent.RemoveChild(this);
                ItemNode.RemoveFromProjectFile();
            }

            ResetProperties();

            HierarchyHelpers.RefreshPropertyBrowser(this);

            return(VSConstants.S_OK);
        }
コード例 #23
0
 public NewItemDialog(ProjectMgr projectManager)
 {
     InitializeComponent();
     this.projectManager = projectManager;
     Owner = Application.Current.MainWindow;
 }
コード例 #24
0
 private void PythonProjectReferenceNode_ProjectLoaded(object sender, ProjectEventArgs e)
 {
     InitializeFileChangeListener();
     AddAnalyzedAssembly(((PythonProjectNode)ProjectMgr).GetInterpreter() as IPythonInterpreterWithProjectReferences).DoNotWait();
     ProjectMgr.OnInvalidateItems(Parent);
 }
コード例 #25
0
        /// <summary>
        /// Creates an assemby or com reference node given a selector data.
        /// </summary>
        protected virtual ReferenceNode CreateFileComponent(VSCOMPONENTSELECTORDATA selectorData)
        {
            if (null == selectorData.bstrFile)
            {
                throw new ArgumentNullException("selectorData");
            }

            // We have a path to a file, it could be anything
            // First see if it is a managed assembly
            bool tryToCreateAnAssemblyReference = true;

            if (File.Exists(selectorData.bstrFile))
            {
                try
                {
                    // We should not load the assembly in the current appdomain.
                    // If we do not do it like that and we load the assembly in the current appdomain then the assembly cannot be unloaded again.
                    // The following problems might arose in that case.
                    // 1. Assume that a user is extending the MPF and  his project is creating a managed assembly dll.
                    // 2. The user opens VS and creates a project and builds it.
                    // 3. Then the user opens VS creates another project and adds a reference to the previously built assembly. This will load the assembly in the appdomain had we been using Assembly.ReflectionOnlyLoadFrom.
                    // 4. Then he goes back to the first project modifies it an builds it. A build error is issued that the assembly is used.

                    // GetAssemblyName is assured not to load the assembly.
                    tryToCreateAnAssemblyReference = (AssemblyName.GetAssemblyName(selectorData.bstrFile) != null);
                }
                catch (BadImageFormatException)
                {
                    // We have found the file and it is not a .NET assembly; no need to try to
                    // load it again.
                    tryToCreateAnAssemblyReference = false;
                }
                catch (FileLoadException)
                {
                    // We must still try to load from here because this exception is thrown if we want
                    // to add the same assembly refererence from different locations.
                    tryToCreateAnAssemblyReference = true;
                }
            }

            ReferenceNode node = null;

            if (tryToCreateAnAssemblyReference)
            {
                // This might be a candidate for an assembly reference node. Try to load it.
                // CreateAssemblyReferenceNode will suppress BadImageFormatException if the node cannot be created.
                node = this.CreateAssemblyReferenceNode(selectorData.bstrFile);
            }

            // If no node has been created try to create a com reference node.
            if (node == null)
            {
                if (!File.Exists(selectorData.bstrFile))
                {
                    return(null);
                }

                node = ProjectMgr.CreateReferenceNodeForFile(selectorData.bstrFile);
            }

            return(node);
        }
コード例 #26
0
ファイル: BaseFileNode.cs プロジェクト: wuchuguang/VisualRust
 protected virtual void OnFileCreated()
 {
     ProjectMgr.ReparseFileNode(this);
 }
コード例 #27
0
        public void UpdateContentType()
        {
            var oldContentType = _contentType;

            _contentType = FolderContentType.None;
            var parent = Parent as NodejsFolderNode;

            _containsNodeOrBrowserFiles = false;

            if (ItemNode.IsExcluded || ItemNode.Url.Contains(NodejsConstants.NodeModulesFolder))
            {
                _contentType = FolderContentType.None;
            }
            else
            {
                // Iterate through all of the javascript files in a directory to determine whether
                // the build actions are Content, Compile, or a mix of the two.
                var nodejsFileNodes           = EnumNodesOfType <NodejsFileNode>();
                FolderContentType contentType = FolderContentType.None;
                foreach (var fileNode in nodejsFileNodes)
                {
                    if (!fileNode.Url.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var properties = fileNode.NodeProperties as IncludedFileNodeProperties;
                    if (properties != null)
                    {
                        _containsNodeOrBrowserFiles = true;
                        switch (properties.BuildAction)
                        {
                        case prjBuildAction.prjBuildActionContent:
                            contentType |= FolderContentType.Browser;
                            break;

                        case prjBuildAction.prjBuildActionCompile:
                            contentType |= FolderContentType.Node;
                            break;
                        }

                        if (contentType == FolderContentType.Mixed)
                        {
                            break;
                        }
                    }
                }

                // If there are no relevant javascript files in the folder, then fall back to
                // the parent type. This enables us to provide good defaults in the event that
                // an item is added to the directory later.
                if (contentType == FolderContentType.None)
                {
                    // Set as parent content type
                    if (parent != null)
                    {
                        contentType = parent.ContentType;
                    }
                }

                _contentType = contentType;
                ProjectMgr.ReDrawNode(this, UIHierarchyElement.Caption);
            }

            // Update the caption of the parent folder accordingly
            if (parent != null && _contentType != oldContentType)
            {
                parent.UpdateContentType();
            }
        }
コード例 #28
0
        private ITextBuffer GetTextBufferOnUIThread(bool create)
        {
            IVsTextManager textMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
            var            model   = GetService(typeof(SComponentModel)) as IComponentModel;
            var            adapter = model.GetService <IVsEditorAdaptersFactoryService>();
            uint           itemid;

            IVsRunningDocumentTable rdt = ProjectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

            if (rdt != null)
            {
                IVsHierarchy      hier;
                IVsPersistDocData persistDocData;
                uint   cookie;
                bool   docInRdt = true;
                IntPtr docData  = IntPtr.Zero;
                int    hr       = NativeMethods.E_FAIL;
                try {
                    //Getting a read lock on the document. Must be released later.
                    hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, GetMkDocument(), out hier, out itemid, out docData, out cookie);
                    if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero)
                    {
                        if (!create)
                        {
                            return(null);
                        }
                        Guid iid = VSConstants.IID_IUnknown;
                        cookie   = 0;
                        docInRdt = false;
                        ILocalRegistry localReg = this.ProjectMgr.GetService(typeof(SLocalRegistry)) as ILocalRegistry;
                        ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData));
                    }
                    persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
                } finally {
                    if (docData != IntPtr.Zero)
                    {
                        Marshal.Release(docData);
                    }
                }

                //Try to get the Text lines
                IVsTextLines srpTextLines = persistDocData as IVsTextLines;
                if (srpTextLines == null)
                {
                    // Try getting a text buffer provider first
                    IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider;
                    if (srpTextBufferProvider != null)
                    {
                        hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines);
                    }
                }

                // Unlock the document in the RDT if necessary
                if (docInRdt && rdt != null)
                {
                    ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie));
                }

                if (srpTextLines != null)
                {
                    return(adapter.GetDocumentBuffer(srpTextLines));
                }
            }

            IWpfTextView view = GetTextView();

            return(view.TextBuffer);
        }
コード例 #29
0
 private void EventListener_AfterActiveSolutionConfigurationChange(object sender, EventArgs e)
 {
     InitializeFileChangeListener();
     AddAnalyzedAssembly(((PythonProjectNode)ProjectMgr).GetInterpreter() as IPythonInterpreterWithProjectReferences).DoNotWait();
     ProjectMgr.OnInvalidateItems(Parent);
 }
コード例 #30
0
ファイル: PropertyPageBase.cs プロジェクト: ugurak/nemerle
 protected void SetPropertyValue(string propertyName, string value)
 {
     ProjectMgr.SetProjectProperty(propertyName, value);
 }