public void AddFromDirectory_EmptyDirectoryInsideProject_ProjectIsSaved()
        {
            CreateProjectItems(@"d:\projects\myproject\myproject.csproj");
            string directory = @"d:\projects\myproject\tools";

            projectItems.AddFromDirectory(directory);

            bool saved = msbuildProject.IsSaved;

            Assert.IsTrue(saved);
        }
Example #2
0
        private void AddProjectFolder(string name, NewItemTarget target)
        {
            // Make sure the directory exists before we add it to the project. Don't
            // use `PackageUtilities.EnsureOutputPath()` because it can silently fail.
            Directory.CreateDirectory(Path.Combine(target.Directory, name));

            // We can't just add the final directory to the project because that will
            // only add the final segment rather than adding each segment in the path.
            // Split the name into segments and add each folder individually.
            ProjectItems items           = target.ProjectItem?.ProjectItems ?? target.Project.ProjectItems;
            string       parentDirectory = target.Directory;

            foreach (string segment in SplitPath(name))
            {
                parentDirectory = Path.Combine(parentDirectory, segment);

                // Look for an existing folder in case it's already in the project.
                ProjectItem folder = items
                                     .OfType <ProjectItem>()
                                     .Where(item => segment.Equals(item.Name, StringComparison.OrdinalIgnoreCase))
                                     .Where(item => item.IsKind(Constants.vsProjectItemKindPhysicalFolder, Constants.vsProjectItemKindVirtualFolder))
                                     .FirstOrDefault();

                if (folder == null)
                {
                    folder = items.AddFromDirectory(parentDirectory);
                }

                items = folder.ProjectItems;
            }
        }
        /// <summary>
        /// Adds a folder to a specified <paramref name="collection"/> of project items.
        /// </summary>
        /// <param name="collection">
        /// A <see cref="ProjectItems"/> collection that belongs to a <see cref="Project"/> or
        /// <see cref="ProjectItem"/> of type <see cref="Constants.vsProjectItemKindPhysicalFolder"/>.
        /// </param>
        /// <param name="folderName">
        /// Name of the folder to be added.
        /// </param>
        /// <param name="basePath">
        /// Absolute path to the directory where the folder is located.
        /// </param>
        /// <returns>
        /// A <see cref="ProjectItem"/> that represents new folder added to the <see cref="Project"/>.
        /// </returns>
        /// <remarks>
        /// If the specified folder doesn't exist in the solution and the file system,
        /// a new folder will be created in both. However, if the specified folder
        /// already exists in the file system, it will be added to the solution instead.
        /// Unfortunately, an existing folder can only be added to the solution with
        /// all of sub-folders and files in it. Thus, if a single output file is
        /// generated in an existing folders not in the solution, the target folder will
        /// be added to the solution with all files in it, generated or not. The
        /// only way to avoid this would be to immediately remove all child items
        /// from a newly added existing folder. However, this could lead to having
        /// orphaned files that were added to source control and later excluded from
        /// the project. We may need to revisit this code and access <see cref="SourceControl"/>
        /// automation model to remove the child items from source control too.
        /// </remarks>
        private static ProjectItem AddFolder(ProjectItems collection, string folderName, string basePath)
        {
            // Does the folder already exist in the solution?
            ProjectItem folder = collection.Cast <ProjectItem>().FirstOrDefault(
                p => string.Compare(p.Name, folderName, StringComparison.OrdinalIgnoreCase) == 0);

            if (folder != null)
            {
                return(folder);
            }

            try
            {
                // Try adding folder to the project.
                // Note that this will work for existing folder in a Database project but not in C#.
                return(collection.AddFolder(folderName, Constants.vsProjectItemKindPhysicalFolder));
            }
            catch (COMException)
            {
                // If folder already exists on disk and the previous attempt to add failed
                string folderPath = Path.Combine(basePath, folderName);
                if (Directory.Exists(folderPath))
                {
                    // Try adding it from disk
                    // Note that this will work in a C# but is not implemented in Database projects.
                    return(collection.AddFromDirectory(folderPath));
                }

                throw;
            }
        }
        private ProjectItem EnsureDirectoryExists(ProjectItems projectItems, string folderName)
        {
            ProjectItem projectItem;

            try
            {
                var projectPath   = projectItems.ContainingProject.Properties.Item("FullPath").Value.ToString();
                var directoryPath = Path.Combine(projectPath, folderName);
                if (Directory.Exists(directoryPath))
                {
                    projectItem = projectItems.AddFromDirectory(directoryPath);
                }
                else
                {
                    projectItem = projectItems.AddFolder(folderName);
                }
            }
            catch (Exception ex)
            {
                var item = GetProjectItems(projectItems, new Comparer(folderName, OperatorType.Equals)).FirstOrDefault(); //GetProjectItems(projectItems, true, false, new Conditioner(folderName, StringComparisonType.Equal)).FirstOrDefault();
                if (item == null)
                {
                    throw new Exception(string.Format("Unknown exception while trying to find directory {0}", folderName));
                }
                projectItem = item;
            }
            return(projectItem);
        }
Example #5
0
 public static void AddItemsToProject(ProjectItems projectItems, IEnumerable <string> paths)
 {
     foreach (var path in paths)
     {
         try
         {
             var itemName = System.IO.Path.GetFileName(path);
             if (System.IO.File.Exists(path))
             {
                 if (Utils.GetProjectItem(projectItems, itemName) == null)
                 {
                     projectItems.AddFromFile(path);
                 }
             }
             else if (System.IO.Directory.Exists(path))
             {
                 var childProjectItem = Utils.GetProjectItem(projectItems, itemName);
                 if (childProjectItem == null)
                 {
                     childProjectItem = projectItems.AddFromDirectory(path);
                 }
                 var childPaths = System.IO.Directory.GetFileSystemEntries(path);
                 AddItemsToProject(childProjectItem.ProjectItems, childPaths);
             }
         }
         catch (InvalidOperationException)
         {
             // Item exists, ignore exception
         }
     }
 }
        private static ProjectItems GetOrCreateFolder(ProjectItems projectItems, string folderName, bool createIfNotExists)
        {
            if (projectItems == null)
            {
                return(null);
            }

            ProjectItem subFolder;

            if (projectItems.TryGetFolder(folderName, out subFolder))
            {
                // Get the sub folder
                return(subFolder.ProjectItems);
            }
            else if (createIfNotExists)
            {
                Property property = ((dynamic)projectItems.Parent).Properties.Item("FullPath");

                Debug.Assert(property != null, "Unable to get full path property from the project item");
                // Get the full path of this folder on disk and add it
                string fullPath = Path.Combine((string)property.Value, folderName);

                return(projectItems.AddFromDirectory(fullPath).ProjectItems);
            }

            return(null);
        }
 public void AddItemsToProject(ProjectItems projectItems, IEnumerable <string> paths)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     foreach (var path in paths)
     {
         try
         {
             var itemName = Path.GetFileName(path);
             if (File.Exists(path))
             {
                 if (GetProjectItem(projectItems, itemName) == null)
                 {
                     projectItems.AddFromFile(path);
                 }
             }
             else if (Directory.Exists(path))
             {
                 var childProjectItem = GetProjectItem(projectItems, itemName);
                 if (childProjectItem == null)
                 {
                     childProjectItem = projectItems.AddFromDirectory(path);
                 }
                 var childPaths = Directory.GetFileSystemEntries(path);
                 AddItemsToProject(childProjectItem.ProjectItems, childPaths);
             }
         }
         catch (InvalidOperationException)
         {
             // Item exists, ignore exception
         }
     }
 }
        // 'parentItem' can be either a Project or ProjectItem
        private static ProjectItem GetOrCreateFolder(object parentItem, string fullPath, string folderName, bool createIfNotExists)
        {
            if (parentItem == null)
            {
                return(null);
            }

            ProjectItems projectItems = GetProjectItems(parentItem);

            if (projectItems.TryGetFolder(folderName, out var subFolder))
            {
                return(subFolder);
            }

            if (!createIfNotExists)
            {
                return(null);
            }

            try
            {
                return(projectItems.AddFromDirectory(fullPath));
            }
            catch (NotImplementedException)
            {
                // This is the case for F#'s project system, we can't add from directory so we fall back to this impl
                return(projectItems.AddFolder(folderName));
            }
        }
Example #9
0
        private static ProjectItems GetOrCreateFolder(ProjectItems projectItems, string folderName, bool createIfNotExists)
        {
            if (projectItems == null)
            {
                return(null);
            }

            ProjectItem subFolder;

            if (projectItems.TryGetFolder(folderName, out subFolder))
            {
                // Get the sub folder
                return(subFolder.ProjectItems);
            }
            else if (createIfNotExists)
            {
                Property property = projectItems.Parent.Properties.Item("FullPath");

                Debug.Assert(property != null, "Unable to get full path property from the project item");
                // Get the full path of this folder on disk and add it
                string fullPath = Path.Combine(property.Value, folderName);

                try {
                    return(projectItems.AddFromDirectory(fullPath).ProjectItems);
                }
                catch (NotImplementedException) {
                    // This is the case for F#'s project system, we can't add from directory so we fall back
                    // to this impl
                    return(projectItems.AddFolder(folderName).ProjectItems);
                }
            }

            return(null);
        }
Example #10
0
        // 'parentItem' can be either a Project or ProjectItem
        private static ProjectItem GetOrCreateFolder(
            Project project,
            object parentItem,
            string fullPath,
            string folderRelativePath,
            string folderName,
            bool createIfNotExists)
        {
            if (parentItem == null)
            {
                return(null);
            }

            ProjectItem subFolder;

            ProjectItems projectItems = GetProjectItems(parentItem);

            if (projectItems.TryGetFolder(folderName, out subFolder))
            {
                // Get the sub folder
                return(subFolder);
            }
            else if (createIfNotExists)
            {
                // The JS Metro project system has a bug whereby calling AddFolder() to an existing folder that
                // does not belong to the project will throw. To work around that, we have to manually include
                // it into our project.
                if (project.IsJavaScriptProject() && Directory.Exists(fullPath))
                {
                    bool succeeded = IncludeExistingFolderToProject(project, folderRelativePath);
                    if (succeeded)
                    {
                        // IMPORTANT: after including the folder into project, we need to get
                        // a new ProjectItems snapshot from the parent item. Otherwise, reusing
                        // the old snapshot from above won't have access to the added folder.
                        projectItems = GetProjectItems(parentItem);
                        if (projectItems.TryGetFolder(folderName, out subFolder))
                        {
                            // Get the sub folder
                            return(subFolder);
                        }
                    }
                    return(null);
                }

                try
                {
                    return(projectItems.AddFromDirectory(fullPath));
                }
                catch (NotImplementedException)
                {
                    // This is the case for F#'s project system, we can't add from directory so we fall back
                    // to this impl
                    return(projectItems.AddFolder(folderName));
                }
            }

            return(null);
        }
Example #11
0
        private ProjectItems WhereToAdd()
        {
            ProjectItems whereToAdd;

            if ((destFolder != String.Empty) && (destFolder != null))
            {
                //only works for a single foldername
                ProjectItem _folder = DteHelper.FindItemByName(this.Project.ProjectItems, destFolder, true);
                if (_folder != null)
                {
                    whereToAdd = _folder.ProjectItems;
                }
                else
                {
                    ProjectItems pitems = this.Project.ProjectItems;

                    string projectpath = Helpers.GetFullPathOfProjectItem(Project);

                    //folder doesnt exist
                    //create the folder
                    char[]   sep     = { '\\' };
                    string[] folders = destFolder.Split(sep);
                    for (int i = 0; i < folders.Length; i++)
                    {
                        projectpath += folders[i] + "\\";
                        //does the folder already exist?
                        _folder = DteHelper.FindItemByName(pitems, folders[i], true);
                        if (_folder != null)
                        {
                            //folder exists
                            pitems = _folder.ProjectItems;
                        }
                        else
                        {   //create folder
                            try
                            {
                                _folder = pitems.AddFolder(folders[i], EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                                pitems  = _folder.ProjectItems;
                            }
                            catch (Exception)
                            {
                                _folder = pitems.AddFromDirectory(projectpath);
                                pitems  = _folder.ProjectItems;
                            }
                        }
                    }
                    whereToAdd = _folder.ProjectItems;
                }
            }
            else
            {
                whereToAdd = this.Project.ProjectItems;
            }
            return(whereToAdd);
        }
Example #12
0
        public ProjectItem FindProjectItemFolderByEntity(Project project, string entityNameSpace)
        {
            ProjectItems answer     = project.ProjectItems;
            ProjectItem  answerItem = null;
            string       answerPath = new FileInfo(project.FullName).Directory.FullName + @"\";

            if (string.IsNullOrEmpty(entityNameSpace) == false)
            {
                string[] dirs = entityNameSpace.Split('.');
                for (int i = 0; i < dirs.Length; i++)
                {
                    string      folderName = dirs[i];
                    ProjectItem folderItem = GetProjectItemInItemsByName(answer, folderName);
                    if (folderItem == null) // اگر پوشه وجود نداشت
                    {
                        string folderPath = answerPath + folderName;
                        if (System.IO.Directory.Exists(folderPath) == false)
                        {
                            answer.AddFolder(folderName);
                        }
                        else
                        {
                            answer.AddFromDirectory(folderPath);
                        }
                    }
                    answerItem = GetProjectItemInItemsByName(answer, folderName);
                    answer     = answerItem.ProjectItems;
                    answerPath = answerItem.FileNames[1];
                }
            }
            else
            {
                return(null);
            }
            return(answerItem);
        }
Example #13
0
        /// <summary>
        /// Adds the files and folders.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="targetProjectType">Type of the target project.</param>
        /// <param name="levels">The number of levels to walk down the chain. If <c>-1</c>, it will handle all levels.</param>
        /// <param name="fileFilter">An enumerable of files that should be handled with care, can be <c>null</c>.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="source" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="target" /> is <c>null</c>.</exception>
        private void AddFilesAndFolders(ProjectItems source, ProjectItems target, ProjectType targetProjectType, int levels, IEnumerable<string> fileFilter)
        {
            Argument.IsNotNull("source", source);
            Argument.IsNotNull("target", target);

            string targetParentName = target.Parent.GetObjectName();

            Log.Debug("Adding files and folders to target '{0}'", targetParentName);

            if (levels == 0)
            {
                return;
            }

            levels--;

            foreach (ProjectItem sourceItem in source)
            {
                var sourceItemName = sourceItem.Name;

                if (sourceItem.IsLinkedFile())
                {
                    Log.Debug("Skipping item '{0}' because it is a linked file (so has another root project)", sourceItem.GetObjectName());

                    continue;
                }

                if (ShouldSkipAddingOfItem(sourceItem, targetProjectType))
                {
                    Log.Debug("Skipping item '{0}' because it is ignored by a rule for target project {1}", sourceItem.GetObjectName(), targetProjectType);

                    continue;
                }

                ProjectItem existingTargetItem = null;
                foreach (ProjectItem targetItem in target)
                {
                    if (string.Equals(targetItem.Name, sourceItemName))
                    {
                        existingTargetItem = targetItem;
                        break;
                    }
                }

                bool isFolder = sourceItem.IsFolder();
                bool containsSubItems = isFolder || sourceItem.ContainsChildItems();

                if (existingTargetItem == null)
                {
                    if (!isFolder)
                    {
                        if (sourceItem.IsXamlFile() && ((targetProjectType == ProjectType.NET40) || (targetProjectType == ProjectType.NET45)))
                        {
                            Log.Debug("File '{0}' is a xaml file and the target project is NET40 or NET45. There is a bug in Visual Studio that does not allow to link xaml files in NET40, so a copy is created.", sourceItem.FileNames[0]);

                            // string targetFile = sourceItem.GetTargetFileName(target);
                            // File.Copy(sourceItem.FileNames[0], targetFile);
                            existingTargetItem = target.AddFromFileCopy(sourceItem.FileNames[0]);
                        }
                        else
                        {
                            Log.Debug("Adding link to file '{0}'", sourceItem.FileNames[0]);

                            try
                            {
                                // Linked file
                                existingTargetItem = target.AddFromFile(sourceItem.FileNames[0]);
                            }
                            catch (Exception ex)
                            {
                                var messageService = ServiceLocator.Default.ResolveType<IMessageService>();
                                messageService.ShowError(ex);
                            }
                        }
                    }
                    else
                    {
                        Log.Debug("Adding folder '{0}'", sourceItem.FileNames[0]);

                        string targetDirectory = sourceItem.GetTargetFileName(target.ContainingProject);
                        existingTargetItem = Directory.Exists(targetDirectory) ? target.AddFromDirectory(targetDirectory) : target.AddFolder(sourceItem.Name);
                    }

                    if (existingTargetItem != null)
                    {
                        Log.Debug("Added item '{0}'", existingTargetItem.Name);
                    }
                }

                bool isResourceFile = sourceItem.IsResourceFile();
                if (isResourceFile)
                {
                    SynchronizeResourceFileProperties(sourceItem, existingTargetItem, targetProjectType);
                }

                if (containsSubItems && !isResourceFile)
                {
                    AddFilesAndFolders(sourceItem.ProjectItems, existingTargetItem.ProjectItems, targetProjectType, levels, fileFilter);
                }
            }

            Log.Debug("Added files and folders to target '{0}'", targetParentName);
        }
Example #14
0
        /// <summary>
        /// Adds a folder to a specified <paramref name="collection" /> of project items.
        /// </summary>
        /// <param name="collection">
        /// A <see cref="ProjectItems" /> collection that belongs to a <see cref="Project" /> or
        /// <see cref="ProjectItem" /> of type <see cref="EnvDTE.Constants.vsProjectItemKindPhysicalFolder" />.
        /// </param>
        /// <param name="folderName">
        /// Name of the folder to be added.
        /// </param>
        /// <param name="basePath">
        /// Absolute path to the directory where the folder is located.
        /// </param>
        /// <returns>
        /// A <see cref="ProjectItem" /> that represents new folder added to the <see cref="Project" />.
        /// </returns>
        /// <remarks>
        /// If the specified folder doesn't exist in the solution and the file system,
        /// a new folder will be created in both. However, if the specified folder
        /// already exists in the file system, it will be added to the solution instead.
        /// Unfortunately, an existing folder can only be added to the solution with
        /// all of sub-folders and files in it. Thus, if a single output file is
        /// generated in an existing folders not in the solution, the target folder will
        /// be added to the solution with all files in it, generated or not. The
        /// only way to avoid this would be to immediately remove all child items
        /// from a newly added existing folder. However, this could lead to having
        /// orphaned files that were added to source control and later excluded from
        /// the project. We may need to revisit this code and access <see cref="SourceControl" />
        /// automation model to remove the child items from source control too.
        /// </remarks>
        private static ProjectItem AddFolder(ProjectItems collection, string folderName, string basePath)
        {
            // Does the folder already exist in the solution?
            ProjectItem folder = collection.Cast<ProjectItem>().FirstOrDefault(p => string.Equals(p.Name, folderName, StringComparison.OrdinalIgnoreCase));
            if (folder != null)
            {
                return folder;
            }

            try
            {
                // Try adding folder to the project.
                // Note that this will work for existing folder in a Database project but not in C#.
                return collection.AddFolder(folderName);
            }
            catch (COMException)
            {
                // If folder already exists on disk and the previous attempt to add failed
                string folderPath = Path.Combine(basePath, folderName);
                if (Directory.Exists(folderPath))
                {
                    // Try adding it from disk
                    // Note that this will work in a C# but is not implemented in Database projects.
                    return collection.AddFromDirectory(folderPath);
                }

                throw;
            }
        }