Ejemplo n.º 1
0
 public int GetItemOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out uint pitemid, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason)
 {
     ppHierarchy = null;
     pitemid = 0;
     pbstrUpdatedProjref = null;
     return VSConstants.S_OK;
 }
        private Node createNodeFromSolutionItem(string projectRef)
        {
            var solution = Application.Solution.Value;

            IVsHierarchy hierarchy= null ;
            uint itemid;

            VSUPDATEPROJREFREASON[] updateReasons = new VSUPDATEPROJREFREASON[1];
            string updatedProjectRef;
            if (solution.GetItemOfProjref(projectRef, out hierarchy,out itemid, out updatedProjectRef,updateReasons ) == 0)
            {
                object objProj;
                hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_ExtObject, out objProj);

                // identify what this thing is
                var pi = objProj as ProjectItem;
                var p = objProj as Project;
                var ce = objProj as CodeElement;

                if(pi!=null)
                {
                    // find the first class inthe project
                    var theClass = findFirstClass(pi);
                    var asm = "";
                    var ns = getNamespace(theClass);
                    var t = theClass.Name ;
                    var startline = theClass.StartPoint.Line;
                    var fullname = theClass.FullName;

                    return new Node()
                    {
                        Assembly = asm,
                        Namespace = ns,
                        Type = t,
                        Member = string.Empty,
                        StartLine = startline,
                        IsClass = true ,
                        FullName = fullname
                    };
                }
            }
            return null;
        }
Ejemplo n.º 3
0
 int IVsSolution.GetProjectOfProjref(string projref, out IVsHierarchy hierarchy, out string updatedProjref, VSUPDATEPROJREFREASON[] updateReason)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Moves files from one part of our project to another.
        /// </summary>
        /// <param name="targetNode">the targetHandler node</param>
        /// <param name="projectReferences">List of projectref string</param>
        /// <param name="dropEffect">The drop effect</param>
        /// <returns>true if succeeded</returns>
        internal bool AddFilesFromProjectReferences(HierarchyNode targetNode, string[] projectReferences, uint dropEffect)
        {
            // Validate input
            if (projectReferences == null)
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "projectReferences");
            }
            if (targetNode == null)
            {
                throw new InvalidOperationException();
            }

            // Build a list
            bool bSourceProjectIsNotThisProject = false;
            foreach (string projectReference in projectReferences)
            {
                if (String.IsNullOrEmpty(projectReference))
                {
                    // bad projectref, bail out
                    return false;
                }

                IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
                if (solution == null)
                {
                    throw new InvalidOperationException();
                }

                if (projectReference.EndsWith("/", StringComparison.Ordinal) || projectReference.EndsWith("\\", StringComparison.Ordinal))
                {
                    Guid projectInstanceGuid;
                    string folder = GetSourceFromFolderReference(projectReference, out projectInstanceGuid);
                    string folderNoTrailingSlash = folder.Substring(0, folder.Length - 1);

                    // Check if the source is not this project if it hasn't been
                    // determined yet.
                    if(!bSourceProjectIsNotThisProject)
                    {
                        if (projectInstanceGuid != this.ProjectIDGuid)
                        {
                            bSourceProjectIsNotThisProject = true;
                        }
                    }

                    string folderName = Path.GetFileName(Path.GetDirectoryName(folder));
                    string newFolderBaseDir = GetBaseDirectoryForAddingFiles(targetNode);
                    string targetPath = Path.Combine(newFolderBaseDir, folderName);

                    DragDropItem newItem = new DragDropItem();
                    newItem.reference = projectReference;
                    newItem.source = folderNoTrailingSlash;
                    newItem.destination = targetPath;
                    newItem.destinationExists = Directory.Exists(targetPath);
                    newItem.isFolder = true;
                    newItem.sourceDirMatchesDestDir = NativeMethods.IsSamePath(folderNoTrailingSlash, targetPath);

                    dropItems.Add(newItem);
                }
                else
                {
                    uint itemidLoc;
                    IVsHierarchy hierarchy;
                    string str;
                    VSUPDATEPROJREFREASON[] reason = new VSUPDATEPROJREFREASON[1];
                    ErrorHandler.ThrowOnFailure(solution.GetItemOfProjref(projectReference, out hierarchy, out itemidLoc, out str, reason));
                    if (hierarchy == null)
                    {
                        throw new InvalidOperationException();
                    }

                    // This will throw invalid cast exception if the hierrachy is not a project.
                    IVsProject project = (IVsProject)hierarchy;

                    string moniker;
                    ErrorHandler.ThrowOnFailure(project.GetMkDocument(itemidLoc, out moniker));

                    HierarchyNode n = targetNode;
                    while ((!(n is ProjectNode)) && (!(n is FolderNode)) && (!this.CanFileNodesHaveChilds || !(n is FileNode)))
                    {
                        n = n.Parent;
                    }

                    Guid projectInstanceGuid;
                    solution.GetGuidOfProject(hierarchy, out projectInstanceGuid);
                    // Check if the source is not this project if it hasn't been
                    // determined yet.
                    if (!bSourceProjectIsNotThisProject)
                    {
                        if (projectInstanceGuid != this.ProjectIDGuid)
                        {
                            bSourceProjectIsNotThisProject = true;
                        }
                    }

                    string filename = Path.GetFileName(moniker);
                    string destination = Path.Combine(this.GetBaseDirectoryForAddingFiles(n), filename);
                    string sourcedir = Path.GetDirectoryName(moniker);
                    string destdir = Path.GetDirectoryName(destination);

                    DragDropItem newItem = new DragDropItem();
                    newItem.reference = projectReference;
                    newItem.source = moniker;
                    newItem.destination = destination;
                    newItem.destinationExists = File.Exists(destination);
                    newItem.isFolder = false;
                    newItem.sourceDirMatchesDestDir = NativeMethods.IsSamePath(sourcedir, destdir);

                    dropItems.Add(newItem);
                }
            }

            // We don't want to copy files that are within any selected directories
            foreach (DragDropItem dropItem1 in dropItems)
            {
                if (dropItem1.isFolder)
                {
                    foreach (DragDropItem dropItem2 in dropItems)
                    {
                        // If this item is underneath a folder also being copied
                        // or moved, then remove it from the list of items to be
                        // copied or moved since the copy/move operation of the
                        // containing folder will handle it.
                        if (!dropItem2.source.Equals(dropItem1.source) && dropItem2.source.StartsWith(dropItem1.source, StringComparison.Ordinal))
                        {
                            // set userCancelled so that this item gets skipped
                            dropItem2.userCancelled = true;
                        }
                    }
                }
            }

            // Check for error cases
            foreach (DragDropItem dropItem in dropItems)
            {
                if (dropItem.userCancelled)
                    continue;

                if (dropItem.isFolder)
                {
                    try
                    {
                        AddFolderFromOtherProject(dropItem.reference, targetNode, dropEffect, true);
                    }
                    catch (CopyPasteException e)
                    {
                        string errorMessage = e.Message;
                        if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
                        {
                            string title = null;
                            OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
                            OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
                            OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
                            VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton);
                            return false;
                        }
                        else
                        {
                            throw new InvalidOperationException(errorMessage);
                        }
                    }
                }
                else
                {
                    try
                    {
                        if (dropItem.sourceDirMatchesDestDir && dropEffect == (uint)DropEffect.Move)
                        {
                            throw new DestionPathSameAsSourceException(filename);
                        }

                        bool bWillHaveCopyOfPrepended = dropItem.sourceDirMatchesDestDir && dropEffect == (uint)DropEffect.Copy;
                        // Check if overwriting is possible.
                        // If not, a dialog box will be shown by SystemCanOverwriteExistingItem
                        // and we should stop processing items.
                        if (!bWillHaveCopyOfPrepended && dropItem.destinationExists && this.SystemCanOverwriteExistingItem(dropItem.source, dropItem.destination) != VSConstants.S_OK)
                        {
                            return false;
                        }
                    }
                    catch (DestionPathSameAsSourceException e)
                    {
                        string errorMessage = e.Message;
                        if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
                        {
                            string title = null;
                            OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
                            OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
                            OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
                            VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton);
                            return false;
                        }
                        else
                        {
                            throw new InvalidOperationException(errorMessage);
                        }
                    }
                }
            }

            bool bAnyWereCancelled = false;
            bool bDoApplyAll = false;
            DialogResult applyAllResult = DialogResult.No;
            // Prompt for files to be overwritten
            for (int i = 0; i < dropItems.Count; i++)
            {
                DragDropItem dropItem = dropItems[i];

                if (dropItem.userCancelled)
                    continue;

                // If the source dir matches the dest dir and we are doing copy
                // then no overwriting will occur. Instead, "Copy of " will be
                // prepended.
                if (dropItem.destinationExists && !(dropItem.sourceDirMatchesDestDir && dropEffect == (uint)DropEffect.Copy))
                {
                    string message = SR.GetString(SR.FileAlreadyExists, Path.GetFileName(dropItem.destination));
                    string title = SR.GetString(SR.FileAlreadyExistsCaption);
                    DialogResult msgboxResult;
                    if (bDoApplyAll)
                    {
                        msgboxResult = applyAllResult;
                    }
                    else
                    {
                        bool bApplyAllChecked;
                        msgboxResult = FileOverwriteDialog.LaunchFileOverwriteDialog(this.Site, message, title, null, FileOverwriteDialog.DefaultButton.Yes, out bApplyAllChecked);
                        if(bApplyAllChecked)
                        {
                            bDoApplyAll = true;
                            applyAllResult = msgboxResult;
                        }
                    }

                    if (msgboxResult == DialogResult.No)
                    {
                        dropItem.userCancelled = true;
                        bAnyWereCancelled = true;
                    }
                    else if (msgboxResult != DialogResult.Yes)
                    {
                        // user cancelled the whole thing
                        return false;
                    }
                }
            }

            // Iteratively add files from projectref
            foreach (DragDropItem dropItem in dropItems)
            {
                if (dropItem.userCancelled)
                    continue;

                if (dropItem.isFolder)
                {
                    AddFolderFromOtherProject(dropItem.reference, targetNode, dropEffect);
                }
                else
                {
                    bool oldHandledOverwrite = this.alreadyHandledOverwritePrompts;
                    this.alreadyHandledOverwritePrompts = true;
                    try
                    {
                        if (!AddFileToNodeFromProjectReference(dropItem.reference, targetNode))
                        {
                            return false;
                        }
                    }
                    finally
                    {
                        this.alreadyHandledOverwritePrompts = oldHandledOverwrite;
                    }
                }
            }

            // If any items were cancelled and the source and target projects
            // differ, return false here so that none of the source items are
            // removed. It would be incorrect to remove all of the source
            // items at this point.
            if (bSourceProjectIsNotThisProject && bAnyWereCancelled)
                return false;

            return true;
        }
        /// <summary>
        /// Adds an item from a project refererence to target node.
        /// </summary>
        /// <param name="projectRef"></param>
        /// <param name="targetNode"></param>
        private bool AddFileToNodeFromProjectReference(string projectRef, HierarchyNode targetNode)
        {
            if (String.IsNullOrEmpty(projectRef))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "projectRef");
            }

            if (targetNode == null)
            {
                throw new ArgumentNullException("targetNode");
            }

            IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
            if (solution == null)
            {
                throw new InvalidOperationException();
            }

            uint itemidLoc;
            IVsHierarchy hierarchy;
            string str;
            VSUPDATEPROJREFREASON[] reason = new VSUPDATEPROJREFREASON[1];
            ErrorHandler.ThrowOnFailure(solution.GetItemOfProjref(projectRef, out hierarchy, out itemidLoc, out str, reason));
            if (hierarchy == null)
            {
                throw new InvalidOperationException();
            }

            // This will throw invalid cast exception if the hierrachy is not a project.
            IVsProject project = (IVsProject)hierarchy;

            string moniker;
            ErrorHandler.ThrowOnFailure(project.GetMkDocument(itemidLoc, out moniker));
            string[] files = new String[1] { moniker };
            VSADDRESULT[] vsaddresult = new VSADDRESULT[1];
            vsaddresult[0] = VSADDRESULT.ADDRESULT_Failure;
            int addResult = targetNode.ProjectMgr.DoAddItem(targetNode.ID, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 0, files, IntPtr.Zero, vsaddresult, AddItemContext.Paste);
            if (addResult != VSConstants.S_OK && addResult != VSConstants.S_FALSE && addResult != (int)OleConstants.OLECMDERR_E_CANCELED)
            {
                ErrorHandler.ThrowOnFailure(addResult);
                return false;
            }
            return (vsaddresult[0] == VSADDRESULT.ADDRESULT_Success);
        }
Ejemplo n.º 6
0
 public int GetProjectOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason)
 {
     throw new Exception("The method or operation is not implemented.");
 }
            /// <summary>
            /// Adds an item from a project refererence to target node.
            /// </summary>
            /// <param name="projectRef"></param>
            /// <param name="targetNode"></param>
            private Addition CanAddFileFromProjectReference(string projectRef, string targetFolder, bool fromFolder = false) {
                Utilities.ArgumentNotNullOrEmpty("projectRef", projectRef);

                IVsSolution solution = Project.GetService(typeof(IVsSolution)) as IVsSolution;
                Utilities.CheckNotNull(solution);

                uint itemidLoc;
                IVsHierarchy hierarchy;
                string str;
                VSUPDATEPROJREFREASON[] reason = new VSUPDATEPROJREFREASON[1];
                if (ErrorHandler.Failed(solution.GetItemOfProjref(projectRef, out hierarchy, out itemidLoc, out str, reason))) {
                    // the file may have been deleted between the copy & paste
                    string path;
                    Guid projectGuid;
                    GetPathAndProjectId(projectRef, out projectGuid, out path);
                    ReportMissingItem(path);
                    return null;
                }

                Utilities.CheckNotNull(hierarchy);

                // This will throw invalid cast exception if the hierrachy is not a project.
                IVsProject project = (IVsProject)hierarchy;
                object isLinkValue;
                bool isLink = false;
                if (ErrorHandler.Succeeded(((IVsHierarchy)project).GetProperty(itemidLoc, (int)__VSHPROPID2.VSHPROPID_IsLinkFile, out isLinkValue))) {
                    if (isLinkValue is bool) {
                        isLink = (bool)isLinkValue;
                    }
                }

                string moniker;
                ErrorHandler.ThrowOnFailure(project.GetMkDocument(itemidLoc, out moniker));

                if (DropEffect == DropEffect.Move && IsBadMove(targetFolder, moniker, true)) {
                    return null;
                }

                if (!File.Exists(moniker)) {
                    Utilities.ShowMessageBox(
                            Project.Site,
                            String.Format("The item '{0}' does not exist in the project directory. It may have been moved, renamed or deleted.", Path.GetFileName(moniker)),
                            null,
                            OLEMSGICON.OLEMSGICON_CRITICAL,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                    return null;
                }

                // Check that the source and destination paths aren't the same since we can't move an item to itself.
                // If they are in fact the same location, throw an error that copy/move will not work correctly.
                if (DropEffect == DropEffect.Move && !CommonUtils.IsSamePath(Path.GetDirectoryName(moniker), Path.GetDirectoryName(targetFolder))) {
                    try {
                        string sourceLinkTarget = NativeMethods.GetAbsolutePathToDirectory(Path.GetDirectoryName(moniker));
                        string destinationLinkTarget = null;

                        // if the directory doesn't exist, just skip this.  We will create it later.
                        if (Directory.Exists(targetFolder)) {
                            try {
                                destinationLinkTarget = NativeMethods.GetAbsolutePathToDirectory(targetFolder);
                            } catch (FileNotFoundException) {
                                // This can occur if the user had a symlink'd directory and deleted the backing directory.
                                Utilities.ShowMessageBox(
                                            Project.Site,
                                            String.Format(
                                                "Unable to find the destination folder."),
                                            null,
                                            OLEMSGICON.OLEMSGICON_CRITICAL,
                                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                                return null;
                            }
                        }

                        // If the paths are the same, we can't really move the file...
                        if (destinationLinkTarget != null && CommonUtils.IsSamePath(sourceLinkTarget, destinationLinkTarget)) {
                            CannotMoveSameLocation(moniker);
                            return null;
                        }
                    } catch (Exception e) {
                        if (e.IsCriticalException()) {
                            throw;
                        }
                        TaskDialog.ForException(Project.Site, e, String.Empty, Project.IssueTrackerUrl).ShowModal();
                        return null;
                    }
                }

                // Begin the move operation now that we are past pre-checks.
                var existingChild = Project.FindNodeByFullPath(moniker);
                if (isLink) {
                    // links we just want to update the link node for...
                    if (existingChild != null) {
                        if (ComUtilities.IsSameComObject(Project, project)) {
                            if (DropEffect != DropEffect.Move) {
                                Utilities.ShowMessageBox(
                                        Project.Site,
                                        String.Format("Cannot copy linked files within the same project. You cannot have more than one link to the same file in a project."),
                                        null,
                                        OLEMSGICON.OLEMSGICON_CRITICAL,
                                        OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                                return null;
                            }
                        } else {
                            Utilities.ShowMessageBox(
                                    Project.Site,
                                    String.Format("There is already a link to '{0}'. You cannot have more than one link to the same file in a project.", moniker),
                                    null,
                                    OLEMSGICON.OLEMSGICON_CRITICAL,
                                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                            return null;
                        }
                    }

                    return new ReparentLinkedFileAddition(Project, targetFolder, moniker);
                }

                string newPath = Path.Combine(targetFolder, Path.GetFileName(moniker));
                if (File.Exists(newPath) &&  
                    CommonUtils.IsSamePath(
                        NativeMethods.GetAbsolutePathToDirectory(newPath), 
                        NativeMethods.GetAbsolutePathToDirectory(moniker))) {
                    newPath = GetCopyName(newPath);
                }

                bool ok = false;
                if (DropEffect == DropEffect.Move && Utilities.IsSameComObject(project, Project)) {
                    if (existingChild != null && existingChild.ItemNode != null && existingChild.ItemNode.IsExcluded) {
                        // https://nodejstools.codeplex.com/workitem/271
                        // The item is excluded, so we don't need to ask if we can rename it.
                        ok = true;
                    } else {
                        ok = Project.Tracker.CanRenameItem(moniker, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags);
                    }
                } else {
                    ok = Project.Tracker.CanAddItems(
                        new[] { newPath },
                        new VSQUERYADDFILEFLAGS[] { VSQUERYADDFILEFLAGS.VSQUERYADDFILEFLAGS_NoFlags });
                }

                if (ok) {
                    if (File.Exists(newPath)) {
                        if (DropEffect == DropEffect.Move &&
                            Utilities.IsSameComObject(project, Project) &&
                            Project.FindNodeByFullPath(newPath) != null) {
                            // if we're overwriting an item, we're moving it, make sure that's ok.
                            // OverwriteFileAddition will handle the remove from the hierarchy
                            if (!Project.Tracker.CanRemoveItems(new[] { newPath }, new[] { VSQUERYREMOVEFILEFLAGS.VSQUERYREMOVEFILEFLAGS_NoFlags })) {
                                return null;
                            }
                        }
                        bool? overwrite = OverwriteAllItems;

                        if (overwrite == null) {
                            OverwriteFileDialog dialog;
                            if (!PromptOverwriteFile(moniker, out dialog)) {
                                return null;
                            }

                            overwrite = dialog.ShouldOverwrite;

                            if (dialog.AllItems) {
                                OverwriteAllItems = overwrite;
                            }
                        }

                        if (overwrite.Value) {
                            return new OverwriteFileAddition(Project, targetFolder, DropEffect, moniker, Path.GetFileName(newPath), project);
                        } else {
                            return SkipOverwriteAddition.Instance;
                        }
                    } else if (Directory.Exists(newPath)) {
                        Utilities.ShowMessageBox(
                            Project.Site,
                            SR.GetString(SR.DirectoryExists, CommonUtils.GetFileOrDirectoryName(newPath)),
                            null,
                            OLEMSGICON.OLEMSGICON_CRITICAL,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                        return null;
                    }

                    if (newPath.Length >= NativeMethods.MAX_PATH) {
                        Utilities.ShowMessageBox(
                            Project.Site,
                            SR.GetString(SR.PathTooLongShortMessage),
                            null,
                            OLEMSGICON.OLEMSGICON_CRITICAL,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                        return null;
                    }
                    return new FileAddition(Project, targetFolder, DropEffect, moniker, Path.GetFileName(newPath), project);
                }
                return null;
            }
Ejemplo n.º 8
0
        // This is for moving files from one part of our project to another.
        /// <include file='doc\Hierarchy.uex' path='docs/doc[@for="HierarchyNode.AddFiles"]/*' />
        public void AddFiles(string[] rgSrcFiles){
            if (rgSrcFiles == null || rgSrcFiles.Length == 0)
                return;
            IVsSolution srpIVsSolution = this.GetService(typeof(IVsSolution)) as IVsSolution;
            if (srpIVsSolution == null)
                return;

            IVsProject ourProj = (IVsProject)this.projectMgr;

            foreach (string file in rgSrcFiles){
                uint itemidLoc;
                IVsHierarchy srpIVsHierarchy;
                string str;
                VSUPDATEPROJREFREASON[] reason = new VSUPDATEPROJREFREASON[1];
                srpIVsSolution.GetItemOfProjref(file, out srpIVsHierarchy, out itemidLoc, out str, reason);
                if (srpIVsHierarchy == null){
                    throw new InvalidOperationException();//E_UNEXPECTED;
                }

                IVsProject srpIVsProject = (IVsProject)srpIVsHierarchy;
                if (srpIVsProject == null){
                    continue;
                }

                string cbstrMoniker;
                srpIVsProject.GetMkDocument(itemidLoc, out cbstrMoniker);
                if (File.Exists(cbstrMoniker)){
                    string[] files = new String[1]{ cbstrMoniker };
                    VSADDRESULT[] vsaddresult = new VSADDRESULT[1];
                    vsaddresult[0] = VSADDRESULT.ADDRESULT_Failure;
                    // bugbug: support dropping into subfolder.
                    ourProj.AddItem(this.projectMgr.hierarchyId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 1, files, IntPtr.Zero, vsaddresult);
                    if (vsaddresult[0] == VSADDRESULT.ADDRESULT_Cancel){
                        break;
                    }
                }
            }
        }
Ejemplo n.º 9
0
        private void TryFindOrigin(string newName, out string origin)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (_fileOrigins.TryGetValue(newName, out origin))
            {
                if (origin != null)
                {
                    return;
                }
            }
            else
            {
                _fileOrigins.Add(newName, null);
            }

            // We haven't got the project file origin for free via OnQueryAddFilesEx
            // So:
            //  1 - The file is really new or
            //  2 - The file is drag&dropped into the project from the solution explorer or
            //  3 - The file is copy pasted into the project from an other project or
            //  4 - The file is added via add existing item or
            //  5 - The file is added via drag&drop from another application (OLE drop)
            //
            // The only way to determine is walking through these options
            SortedList <string, string> nameToItem = new SortedList <string, string>();

            nameToItem[Path.GetFileName(newName)] = newName;
            foreach (KeyValuePair <string, string> kv in _fileOrigins)
            {
                if (kv.Value != null)
                {
                    continue;
                }

                nameToItem[Path.GetFileName(kv.Key)] = kv.Key;
            }

            // 2 -  If the file is drag&dropped in the solution explorer
            //      the current selection is still the original selection

            // **************** Check the current selection *************
            // Checks for drag&drop actions. The selection contains the original list of files
            // BH: resx files are not correctly included if we don't retrieve this list recursive
            foreach (string file in SelectionContext.GetSelectedFiles(true))
            {
                if (_fileOrigins.ContainsKey(file))
                {
                    continue;
                }

                string name = Path.GetFileName(file);
                if (nameToItem.ContainsKey(name))
                {
                    string item = nameToItem[name];

                    CheckForMatch(item, file);
                }
            }

            // **************** Check the clipboard *********************
            // 3 - Copy & Paste in the solution explorer:
            //     The original hierarchy information is still on the clipboard

            IDataObject dataObject;
            string      projectItemType;

            if (null != (dataObject = SafeGetDataObject()) && SolutionExplorerClipboardItem.CanRead(dataObject, out projectItemType))
            {
                IVsSolution       solution = GetService <IVsSolution>(typeof(SVsSolution));
                ISccProjectWalker walker   = GetService <ISccProjectWalker>();

                foreach (string projref in SolutionExplorerClipboardItem.DecodeProjectItemData(dataObject, projectItemType))
                {
                    IVsHierarchy project;
                    uint         itemid;
                    {
                        string updatedRef;
                        VSUPDATEPROJREFREASON[] updateReason = new VSUPDATEPROJREFREASON[1];
                        if (!VSErr.Succeeded(solution.GetItemOfProjref(projref, out project, out itemid, out updatedRef, updateReason)))
                        {
                            continue;
                        }
                    }

                    foreach (string rawFile in walker.GetSccFiles(project, itemid, ProjectWalkDepth.AllDescendantsInHierarchy, null))
                    {
                        if (!SvnItem.IsValidPath(rawFile))
                        {
                            continue;
                        }

                        string file = SvnTools.GetNormalizedFullPath(rawFile);

                        if (_fileOrigins.ContainsKey(file))
                        {
                            continue;
                        }

                        string name = Path.GetFileName(file);
                        if (nameToItem.ContainsKey(name))
                        {
                            string item = nameToItem[name];

                            CheckForMatch(item, file);
                        }
                    }
                }
            }


            // **************** Check external hints ********************
            // Checks for HandsOff events send by the project system
            foreach (string file in _fileHints)
            {
                if (_fileOrigins.ContainsKey(file))
                {
                    continue;
                }

                string name = Path.GetFileName(file);
                if (nameToItem.ContainsKey(name))
                {
                    string item = nameToItem[name];

                    CheckForMatch(item, file);
                }
            }

            // The clipboard seems to have some other format which might contain other info
            origin = _fileOrigins[newName];

            if (origin == null)
            {
                bool   first = true;
                string path  = null;

                foreach (KeyValuePair <string, string> kv in _fileOrigins)
                {
                    if (kv.Value == null)
                    {
                        continue;
                    }

                    if (SvnItem.IsBelowRoot(kv.Key, newName))
                    {
                        string itemRoot = kv.Value.Substring(0, kv.Value.Length - kv.Key.Length + newName.Length);
                        if (first)
                        {
                            path  = itemRoot;
                            first = false;
                        }
                        else if (path != itemRoot)
                        {
                            origin = null;
                            return;
                        }
                    }
                }
                origin = path;
            }
        }
 public int GetProjectOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason) {
     throw new NotImplementedException();
 }
 public int GetItemOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out uint pitemid, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason) {
     var comps = pszProjref.Split('|');
     if (comps.Length == 3) {
         foreach (var project in _projects.Values) {
             if (project.Filename == comps[1]) {
                 ppHierarchy = project.Hierarchy;
                 if (ErrorHandler.Succeeded(project.Hierarchy.ParseCanonicalName(comps[2], out pitemid))) {
                     pbstrUpdatedProjref = pszProjref;
                     puprUpdateReason[0] = VSUPDATEPROJREFREASON.UPR_NoUpdate;
                     return VSConstants.S_OK;
                 }
             }
         }
     }
     ppHierarchy = null;
     pitemid = 0;
     pbstrUpdatedProjref = null;
     return VSConstants.E_FAIL;
 }
Ejemplo n.º 12
0
		public int GetProjectOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason)
		{
			ppHierarchy = null;
			pbstrUpdatedProjref = null;
			return VSConstants.E_NOTIMPL;
		}
Ejemplo n.º 13
0
 int IVsSolution.GetItemOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out uint pitemid, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 14
0
            /// <summary>
            /// Adds an item from a project refererence to target node.
            /// </summary>
            /// <param name="projectRef"></param>
            /// <param name="targetNode"></param>
            private Addition CanAddFileFromProjectReference(string projectRef, string targetFolder, bool fromFolder = false) {
                Utilities.ArgumentNotNullOrEmpty("projectRef", projectRef);

                IVsSolution solution = Project.GetService(typeof(IVsSolution)) as IVsSolution;
                Utilities.CheckNotNull(solution);

                uint itemidLoc;
                IVsHierarchy hierarchy;
                string str;
                VSUPDATEPROJREFREASON[] reason = new VSUPDATEPROJREFREASON[1];
                if (ErrorHandler.Failed(solution.GetItemOfProjref(projectRef, out hierarchy, out itemidLoc, out str, reason))) {
                    // the file may have been deleted between the copy & paste
                    string path;
                    Guid projectGuid;
                    GetPathAndProjectId(projectRef, out projectGuid, out path);
                    ReportMissingItem(path);
                    return null;
                }

                Utilities.CheckNotNull(hierarchy);

                // This will throw invalid cast exception if the hierrachy is not a project.
                IVsProject project = (IVsProject)hierarchy;

                string moniker;
                ErrorHandler.ThrowOnFailure(project.GetMkDocument(itemidLoc, out moniker));

                if (DropEffect == DropEffect.Move && IsBadMove(targetFolder, moniker, true)) {
                    return null;
                }

                if (!File.Exists(moniker)) {
                    VsShellUtilities.ShowMessageBox(
                            Project.Site,
                            String.Format("The item '{0}' does not exist in the project directory. It may have been moved, renamed or deleted.", Path.GetFileName(moniker)),
                            null,
                            OLEMSGICON.OLEMSGICON_CRITICAL,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                    return null;
                }

                string newPath = Path.Combine(targetFolder, Path.GetFileName(moniker));
                var existingChild = Project.FindNodeByFullPath(moniker);
                if (existingChild != null && existingChild.IsLinkFile) {
                    if (DropEffect == DropEffect.Move) {
                        // moving a link file, just update it's location in the hierarchy
                        return new ReparentLinkedFileAddition(Project, targetFolder, moniker);
                    } else {
                        // 
                        VsShellUtilities.ShowMessageBox(
                                Project.Site,
                                String.Format("Cannot copy linked files within the same project. You cannot have more than one link to the same file in a project."),
                                null,
                                OLEMSGICON.OLEMSGICON_CRITICAL,
                                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                        return null;
                    }
                } else if (File.Exists(newPath) && CommonUtils.IsSamePath(newPath, moniker)) {
                    newPath = GetCopyName(newPath);
                }

                bool ok = false;
                if (DropEffect == DropEffect.Move && Utilities.IsSameComObject(project, Project)) {
                    ok = Project.Tracker.CanRenameItem(moniker, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags);
                } else {
                    ok = Project.Tracker.CanAddItems(
                        new[] { newPath },
                        new VSQUERYADDFILEFLAGS[] { VSQUERYADDFILEFLAGS.VSQUERYADDFILEFLAGS_NoFlags });
                }

                if (ok) {
                    if (File.Exists(newPath)) {
                        if (DropEffect == DropEffect.Move &&
                            Utilities.IsSameComObject(project, Project) &&
                            Project.FindNodeByFullPath(newPath) != null) {
                            // if we're overwriting an item, we're moving it, make sure that's ok.
                            // OverwriteFileAddition will handle the remove from the hierarchy
                            if (!Project.Tracker.CanRemoveItems(new[] { newPath }, new[] { VSQUERYREMOVEFILEFLAGS.VSQUERYREMOVEFILEFLAGS_NoFlags })) {
                                return null;
                            }
                        }
                        bool? overwrite = OverwriteAllItems;

                        if (overwrite == null) {
                            var dialog = new OverwriteFileDialog(String.Format("A file with the name '{0}' already exists.  Do you want to replace it?", Path.GetFileName(moniker)), true);
                            dialog.Owner = Application.Current.MainWindow;
                            bool? dialogResult = dialog.ShowDialog();

                            if (dialogResult != null && !dialogResult.Value) {
                                // user cancelled
                                return null;
                            }

                            overwrite = dialog.ShouldOverwrite;

                            if (dialog.AllItems) {
                                OverwriteAllItems = overwrite;
                            }
                        }

                        if (overwrite.Value) {
                            return new OverwriteFileAddition(Project, targetFolder, DropEffect, moniker, Path.GetFileName(newPath), project);
                        } else {
                            return NopAddition.Instance;
                        }
                    }

                    if (newPath.Length >= NativeMethods.MAX_PATH) {
                        VsShellUtilities.ShowMessageBox(
                            Project.Site,
                            "The filename is too long.",
                            null,
                            OLEMSGICON.OLEMSGICON_CRITICAL,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                        return null;
                    }
                    return new FileAddition(Project, targetFolder, DropEffect, moniker, Path.GetFileName(newPath), project);
                }
                return null;
            }