コード例 #1
0
        /// <summary>
        /// Saves and configures the additional output created by the transformation.
        /// </summary>
        /// <remarks>
        /// Note that this method currently cannot distinguish between files that are
        /// already in a Database project and files that are simply displayed with
        /// "Show All Files" option. Database project model makes these items appear
        /// as if they were included in the project.
        /// </remarks>
        private void ConfigureOutputFile(OutputFile output)
        {
            string outputFilePath = this.GetFullPath(output.Path);

            ProjectItem  outputItem = this.dte.Solution.FindProjectItem(outputFilePath);
            ProjectItems collection = this.FindProjectItemCollection(output);

            if (outputItem == null)
            {
                // If output file has not been added to the solution
                outputItem = collection.AddFromFile(outputFilePath);
            }
            else if (!Same(outputItem.Collection, collection))
            {
                // If the output file moved from one collection to another
                string backupFile = outputFilePath + ".bak";
                File.Move(outputFilePath, backupFile); // Prevent unnecessary source control operations
                outputItem.Delete();                   // Remove doesn't work on "DependentUpon" items
                File.Move(backupFile, outputFilePath);

                outputItem = collection.AddFromFile(outputFilePath);
            }

            ConfigureProjectItem(outputItem, output);
        }
コード例 #2
0
        /// <summary>
        /// Saves content accumulated by this transformation to the output files.
        /// </summary>
        /// <param name="outputFiles">
        /// <see cref="OutputFile"/>s that need to be added to the <paramref name="solution"/>.
        /// </param>
        /// <param name="solution">
        /// Current Visual Studio <see cref="Solution"/>.
        /// </param>
        /// <param name="projects">
        /// All <see cref="Project"/>s in the current <paramref name="solution"/>.
        /// </param>
        /// <param name="template">
        /// A <see cref="ProjectItem"/> that represents T4 template being transformed.
        /// </param>
        /// <remarks>
        /// Note that this method currently cannot distinguish between files that are
        /// already in a Database project and files that are simply displayed with
        /// "Show All Files" option. Database project model makes these items appear
        /// as if they were included in the project.
        /// </remarks>
        private static void UpdateOutputFiles(IEnumerable <OutputFile> outputFiles, Solution solution, IEnumerable <Project> projects, ProjectItem template)
        {
            foreach (OutputFile output in outputFiles)
            {
                UpdateOutputFile(output); // Save the output file before we can add it to the solution

                ProjectItem  outputItem = solution.FindProjectItem(output.File);
                ProjectItems collection = FindProjectItemCollection(output, projects, template);

                if (outputItem == null)
                {
                    // If output file has not been added to the solution
                    outputItem = collection.AddFromFile(output.File);
                }
                else if (!Same(outputItem.Collection, collection))
                {
                    // If the output file moved from one collection to another
                    string backupFile = output.File + ".bak";
                    File.Move(output.File, backupFile); // Prevent unnecessary source control operations
                    outputItem.Delete();                // Remove doesn't work on "DependentUpon" items
                    File.Move(backupFile, output.File);

                    outputItem = collection.AddFromFile(output.File);
                }

                SetProjectItemProperties(outputItem, output);
                SetProjectItemBuildProperties(outputItem, output);
                AddProjectItemReferences(outputItem, output);
            }
        }
コード例 #3
0
ファイル: TemplatesCopying.cs プロジェクト: kouweizhong/waqs
        public static void AddItem(string ttInclude, string vsVersion, string netVersion, string ttIncludeName, string templatesFolder, HashSet <string> existingTTIncludes, ProjectItems templatesProjectItems)
        {
            var m = Regex.Match(ttInclude, @".(NET\d+).");

            if (!m.Success || m.Groups[1].Value == netVersion)
            {
                const string x64Key = @"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows";
                if (ttIncludeName.EndsWith(".x64"))
                {
                    try
                    {
                        if (Registry.LocalMachine.OpenSubKey(x64Key) == null)
                        {
                            return;
                        }
                        ttIncludeName = ttIncludeName.Substring(0, ttIncludeName.Length - 4);
                    }
                    catch
                    {
                        return;
                    }
                }
                else if (ttIncludeName.EndsWith(".x86"))
                {
                    try
                    {
                        if (Registry.LocalMachine.OpenSubKey(x64Key) != null)
                        {
                            return;
                        }
                    }
                    catch
                    {
                    }
                    ttIncludeName = ttIncludeName.Substring(0, ttIncludeName.Length - 4);
                }
                var ttIncludeCopy = Path.Combine(templatesFolder, ttIncludeName);
                if (!existingTTIncludes.Contains(ttIncludeName))
                {
                    templatesProjectItems.AddFromFile(ttIncludeCopy);
                }
                if (ttIncludeName.Contains("." + vsVersion + "." + netVersion + "."))
                {
                    ttIncludeCopy = ttIncludeCopy.Substring(0, ttIncludeCopy.Length - 10) + ".merge.tt";
                    ttIncludeName = Path.GetFileName(ttIncludeCopy);
                    if (!existingTTIncludes.Contains(ttIncludeName))
                    {
                        templatesProjectItems.AddFromFile(ttIncludeCopy);
                    }
                }
            }
        }
コード例 #4
0
ファイル: TemplatesCopying.cs プロジェクト: bnjMichel/waqs
 public static void AddItem(string ttInclude, string vsVersion, string netVersion, string ttIncludeName, string templatesFolder, HashSet<string> existingTTIncludes, ProjectItems templatesProjectItems)
 {
     var m = Regex.Match(ttInclude, @".(NET\d+).");
     if (!m.Success || m.Groups[1].Value == netVersion)
     {
         const string x64Key = @"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows";
         if (ttIncludeName.EndsWith(".x64"))
         {
             try
             {
                 if (Registry.LocalMachine.OpenSubKey(x64Key) == null)
                 {
                     return;
                 }
                 ttIncludeName = ttIncludeName.Substring(0, ttIncludeName.Length - 4);
             }
             catch
             {
                 return;
             }
         }
         else if (ttIncludeName.EndsWith(".x86"))
         {
             try
             {
                 if (Registry.LocalMachine.OpenSubKey(x64Key) != null)
                 {
                     return;
                 }
             }
             catch
             {
             }
             ttIncludeName = ttIncludeName.Substring(0, ttIncludeName.Length - 4);
         }
         var ttIncludeCopy = Path.Combine(templatesFolder, ttIncludeName);
         if (!existingTTIncludes.Contains(ttIncludeName))
         {
             templatesProjectItems.AddFromFile(ttIncludeCopy);
         }
         if (ttIncludeName.Contains("." + vsVersion + "." + netVersion + "."))
         {
             ttIncludeCopy = ttIncludeCopy.Substring(0, ttIncludeCopy.Length - 10) + ".merge.tt";
             ttIncludeName = Path.GetFileName(ttIncludeCopy);
             if (!existingTTIncludes.Contains(ttIncludeName))
             {
                 templatesProjectItems.AddFromFile(ttIncludeCopy);
             }
         }
     }
 }
コード例 #5
0
 private static void CopyProjectItems(ProjectItems sourceItems, ProjectItems targetItems)
 {
     foreach (ProjectItem projectItem in sourceItems)
     {
         ProjectItem tempItem = null;
         try
         {
             tempItem = targetItems.Item(projectItem.Name);
         }
         catch (ArgumentException)
         {
             if (projectItem.Kind == "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}")
             {
                 if (projectItem.Name != "Properties")
                 {
                     tempItem = targetItems.AddFolder(projectItem.Name);
                 }
             }
             else if (projectItem.Name != "packages.config")
             {
                 tempItem = targetItems.AddFromFile(projectItem.Properties.Item("LocalPath").Value as string);
             }
         }
         if (tempItem != null)
         {
             CopyProjectItems(projectItem.ProjectItems, tempItem.ProjectItems);
         }
     }
 }
コード例 #6
0
        private void AddFromFileWithFolders(ProjectItems root, string name, string dir)
        {
            string pathToNow = null;
            var    tmp       = name.Split('\\');

            for (int i = 0; i < tmp.Length - 1; i++)
            {
                string thisDir = tmp[i];
                pathToNow = pathToNow == null ? thisDir : Path.Combine(pathToNow, thisDir);

                var item = Find(root, thisDir);
                if (item == null)
                {
                    //AddExistingFolder(root.ContainingProject, pathToNow);

                    //item = Find(root, thisDir);
                    //if (item == null)
                    item = root.AddFolder(thisDir);
                }

                root = item.ProjectItems;
            }

            if (Find(root, tmp[tmp.Length - 1]) == null)
            {
                root.AddFromFile(Path.Combine(dir, name));
            }
        }
コード例 #7
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
         }
     }
 }
コード例 #8
0
 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
         }
     }
 }
コード例 #9
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            DTE2 dte2 = (DTE2)Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(DTE));

            object[] selectedItems = (object[])dte2.ToolWindows.SolutionExplorer.SelectedItems;
            foreach (UIHierarchyItem selectedUIHierarchyItem in selectedItems)
            {
                //if (selectedUIHierarchyItem.Collection.Count > 1)
                if (selectedItems.Length > 1)
                {
                    MessageBox.Show("Please select only one project.", "Error");
                    MessageBox.Show("Length = " + selectedItems.Length + "and: " + selectedUIHierarchyItem.Collection.Count);
                }
                else
                {
                    Project selectedProject = selectedUIHierarchyItem.Object as Project;
                    if (selectedProject != null)
                    {
                        string       pathToAddFileTo = Path.GetDirectoryName(selectedProject.FullName);
                        string       filePath        = ShowScreens(pathToAddFileTo);
                        DTE          dte1            = (DTE)Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(DTE));
                        ProjectItems projectItems    = selectedProject.ProjectItems;
                        projectItems.AddFromFile(filePath);
                    }
                }
            }
        }
コード例 #10
0
        private ProjectItem AddDocumentToProjectItems(
            IVisualStudioHostProject hostProject,
            ProjectItems projectItems,
            DocumentId documentId,
            string folderPath,
            string documentName,
            SourceCodeKind sourceCodeKind,
            SourceText initialText,
            string filePath,
            bool isAdditionalDocument)
        {
            if (filePath == null)
            {
                var baseName   = Path.GetFileNameWithoutExtension(documentName);
                var extension  = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind);
                var uniqueName = projectItems.GetUniqueName(baseName, extension);
                filePath = Path.Combine(folderPath, uniqueName);
            }

            if (initialText != null)
            {
                using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8))
                {
                    initialText.Write(writer);
                }
            }

            using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId))
            {
                return(projectItems.AddFromFile(filePath));
            }
        }
コード例 #11
0
        private void duplicateFiles(ProjectItems projItems)
        {
            ProjectItem projItem;

            for (int i = 1; i <= projItems.Count; i++)
            {
                projItem = projItems.Item(i);
                Debug.Write(projItem.Name + "  " + projItem.Kind);
                try
                {
                    if (projItem.ProjectItems.Count > 0)
                    {
                        duplicateFiles(projItem.ProjectItems);
                    }
                    else if (selectedProjectItems.Contains(projItem))
                    {
                        selectedProjectItems.Remove(projItem);
                        String newPath = copyFile(projItem);
                        if (newPath != null)
                        {
                            try
                            {
                                lastAdded = projItems.AddFromFile(newPath);
                            }
                            catch (Exception) { }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }
コード例 #12
0
ファイル: VsManager.cs プロジェクト: bordev/Tobasco
        private ProjectItem FindProjectItem(ProjectItems items, string fullName)
        {
            ProjectItem item = (from i in items.Cast <ProjectItem>()
                                where i.Name == Path.GetFileName(fullName)
                                select i).FirstOrDefault();

            if (item == null)
            {
                File.CreateText(fullName);
                item = items.AddFromFile(fullName);
            }

            return(item);
        }
    private ProjectItem AddFileToProject (ProjectItems projectItems, string licenseHeaderDefinitionFileName)
    {
      int fileCountBefore = projectItems.Count;
      var newProjectItem = projectItems.AddFromFile (licenseHeaderDefinitionFileName);

      int fileCountAfter = projectItems.Count;
      if (fileCountBefore == fileCountAfter)
      {
        MessageBox.Show (Resources.Warning_CantLinkItemInSameProject, Resources.NameOfThisExtension, MessageBoxButton.OK,
          MessageBoxImage.Information);
      }

      return newProjectItem;
    }
コード例 #14
0
        /// <summary>
        /// The method that creates a new item from the intput string.
        /// </summary>
        public override void Execute()
        {
            // This method is not implemented.
            //projectItem = targetProjectItems.AddFromDirectory(sourceFilePath);

            List <ProjectItem> items = new List <ProjectItem>();

            string[] fileNames = Directory.GetFiles(sourceFilePath, searchPattern);
            foreach (string fileName in fileNames)
            {
                items.Add(targetProjectItems.AddFromFile(fileName));
            }
            projectItems = items.ToArray();
        }
コード例 #15
0
        protected static ProjectItem CreateTestProjectItemFromFile(ProjectItems projectItems, string fileName)
        {
            if (projectItems == null)
            {
                throw new ArgumentNullException("projectItems");
            }

            if (!File.Exists(fileName))
            {
                File.WriteAllText(fileName, string.Empty);
            }

            return(projectItems.AddFromFile(fileName));
        }
コード例 #16
0
        private ProjectItem AddFileToProject(ProjectItems projectItems, string licenseHeaderDefinitionFileName)
        {
            int fileCountBefore = projectItems.Count;
            var newProjectItem  = projectItems.AddFromFile(licenseHeaderDefinitionFileName);

            int fileCountAfter = projectItems.Count;

            if (fileCountBefore == fileCountAfter)
            {
                MessageBox.Show(Resources.Warning_CantLinkItemInSameProject, Resources.NameOfThisExtension, MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }

            return(newProjectItem);
        }
コード例 #17
0
        private static ProjectItem AddFileToProject(ProjectItems projectItems, string licenseHeaderDefinitionFileName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var fileCountBefore = projectItems.Count;
            var newProjectItem  = projectItems.AddFromFile(licenseHeaderDefinitionFileName);

            var fileCountAfter = projectItems.Count;

            if (fileCountBefore == fileCountAfter)
            {
                MessageBoxHelper.ShowMessage(Resources.Warning_CantLinkItemInSameProject);
            }


            return(newProjectItem);
        }
コード例 #18
0
        public void AddFromFile_FullFileNameIsInsideProject_FileIsAddedToProject()
        {
            CreateProjectItems(@"d:\projects\myproject\myproject.csproj");
            string fileName = @"d:\projects\myproject\tools\test.cs";

            msbuildProject.ItemTypeToReturnFromGetDefaultItemType = ItemType.Page;
            projectItems.AddFromFile(fileName);

            var fileItem = msbuildProject.Items.First() as FileProjectItem;

            Assert.AreEqual(@"tools\test.cs", fileItem.Include);
            Assert.AreEqual(@"d:\projects\myproject\tools\test.cs", fileItem.FileName.ToString());
            Assert.AreEqual(ItemType.Page, fileItem.ItemType);
            Assert.AreEqual(msbuildProject, fileItem.Project);
        }
コード例 #19
0
        private void RecursiveIterateProjectItems(ProjectItems items, string folderPath)
        {
            Dictionary <string, FileSearchItem> files;

            if (this.searchedFiles.TryGetValue(folderPath, out files))
            {
                foreach (KeyValuePair <string, FileSearchItem> file in files)
                {
                    ProjectItem item = items.AddFromFile(file.Key);
                    this.SetItemProperties(item, file.Value);
                }
            }
            foreach (ProjectItem item in items)
            {
                this.RecursiveIterateProjectItems(item.ProjectItems, this.NormalizeFolderPath(folderPath + Path.DirectorySeparatorChar + item.Name));
            }
        }
コード例 #20
0
        ///// <summary>
        ///// Ensuures that a project of a given name exists in the solution
        ///// </summary>
        ///// <param name="store">Model from which to look for</param>
        ///// <param name="relativePath">Relative path where to create the new project if necessary (ending in the project name with .csproj)</param>
        ///// <param name="sourcePath">Source path of the template of the project</param>
        ///// <param name="updateAssemblyNameAndNamespace">Should we update the assembly name and namespace of the new project.</param>
        ///// <remarks>
        ///// Suppose you want to create add a new project named "MyProject.csproj" from a template (vs vsTemplate located in a sub folder of the location of the extension,
        ///// and you want to have similar namespaces:
        ///// <code>
        /////    StoreHostingProject.EnsureNamedProjectExistsInDslSolution(dsl.Store, "MyProject.csproj"
        /////                                          , Path.Combine(Path.GetDirectoryName(typeof(ATypeInMyExtension).Assembly.Location), @"Templates\MyProject\MyTemplate.vstemplate")
        /////                                          , true
        /////                                          );
        ///// </code>
        ///// </remarks>
        //public static void EnsureNamedProjectExistsInDslSolution(Store store, string relativePath, string sourcePath, bool updateAssemblyNameAndNamespace)
        //{
        //    // Verify that the relative path ends with csproj
        //    if (Path.GetExtension(relativePath) != ".csproj")
        //    {
        //        throw new ArgumentException("relativePath should be relative path of the .csproj file to create with respect to the solution, hence ending in .csproj", "relativePath");
        //    }

        //    Project project = Store2DTE.GetProjectForStore(store);
        //    Solution solution = project.DTE.Solution;
        //    Project newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.UniqueName == relativePath);
        //    if (newProject != null)
        //    {
        //        return;
        //    }

        //    string projectDirectory = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(project.FullName)), Path.GetFileNameWithoutExtension(relativePath));
        //    string projectPath = Path.Combine(projectDirectory, Path.GetFileName(relativePath));
        //    string projectSimpleName = Path.GetFileNameWithoutExtension(relativePath);

        //    // The project exist but is not in the solution: let's just add it.
        //    if (File.Exists(projectPath))
        //    {
        //        solution.AddFromFile(projectPath, false);
        //    }

        //    // The project does not exist: create it from a template
        //    else
        //    {
        //        newProject = project.DTE.Solution.AddFromTemplate(sourcePath, projectDirectory, Path.GetFileName(relativePath), false);

        //        // Well known workaround for C# and VB projects, AddFromTemplate returns null
        //        newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.Name == projectSimpleName);

        //        // Update the assembly name and namespace if necessary
        //        if (updateAssemblyNameAndNamespace)
        //        {
        //            newProject.Properties.Item("AssemblyName").Value = project.Properties.Item("AssemblyName").Value.ToString().Replace("." + project.Name, "." + projectSimpleName);
        //            newProject.Properties.Item("DefaultNamespace").Value = project.Properties.Item("DefaultNamespace").Value.ToString() + "." + projectSimpleName;
        //        }

        //    }
        //}
        #endregion

        #region Adding a file or a link to a file
        /// <summary>
        /// Ensures that a file is present in the project
        /// </summary>
        /// <param name="store">Store containing a model</param>
        /// <param name="relativePath">relative path where the file should be located</param>
        /// <param name="sourcePath">Path of the file to copy if not already present in the solution</param>
        /// <example>
        /// if you have a file Adapter.tt, added to the VSIX, of type Content, and copied if newer, in a folder Temmplates of the extension project, you can add
        /// it to the GeneratedCode folder of the DSL by the following code:
        /// <code>
        ///    StoreHostingProject.EnsureFileInProject(dsl.Store, @"GeneratedCode\Adapter.tt",
        ///                                            Path.Combine(Path.GetDirectoryName(typeof(MyExtensionAuthoring).Assembly.Location), @"Templates\Adapter.tt"));
        /// </code>
        /// </example>
        public static void EnsureFileCopiedInDslProject(Store store, string relativePath, string sourcePath)
        {
            Contract.Requires(store != null);
            Contract.Requires(relativePath != null);
            Contract.Requires(sourcePath != null);

            Project project = Store2DTE.GetProjectForStore(store);

            string[] pathSegments = relativePath.Split('\\');

            ProjectItems parent = project.ProjectItems;

            // Find the folder (or create it if necessary)
            for (int i = 0; i < pathSegments.Length - 1; ++i)
            {
                ProjectItem folder = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[i]);
                if (folder == null)
                {
                    folder = parent.AddFolder(pathSegments[i]);
                }

                parent = folder.ProjectItems;
            }

            // Find the file and create it if necessary
            ProjectItem file = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[pathSegments.Length - 1]);

            if (file == null)
            {
                string fileDirectory = Path.Combine(Path.GetDirectoryName(project.FullName), Path.GetDirectoryName(relativePath));
                string filePath      = Path.Combine(fileDirectory, Path.GetFileName(relativePath));

                // Case where the file is already there, but not added to the project
                if (File.Exists(filePath))
                {
                    parent.AddFromFile(filePath);
                }
                else
                {
                    parent.AddFromFileCopy(sourcePath);
                }
            }
        }
コード例 #21
0
        public void AddFromFile_AddFromFileFromProjectItemsBelongingToFile_FileIsAddedAsDependentFile()
        {
            CreateProjectItems(@"d:\projects\myproject\myproject.csproj");
            msbuildProject.AddFile("MainForm.cs");
            string fileName = @"d:\projects\myproject\MainForm.Designer.cs";

            msbuildProject.ItemTypeToReturnFromGetDefaultItemType = ItemType.Page;
            projectItems = (ProjectItems)project.ProjectItems.Item("MainForm.cs").ProjectItems;

            projectItems.AddFromFile(fileName);

            FileProjectItem fileItem = msbuildProject.FindFile(new FileName(fileName));

            Assert.AreEqual("MainForm.Designer.cs", fileItem.Include);
            Assert.AreEqual(fileName, fileItem.FileName.ToString());
            Assert.AreEqual(ItemType.Page, fileItem.ItemType);
            Assert.AreEqual(msbuildProject, fileItem.Project);
            Assert.AreEqual("MainForm.cs", fileItem.DependentUpon);
        }
コード例 #22
0
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try
            {
                string entitiesDir = _template.path;

                string nameSpaceStr = _rootNamespace;
                string path         = _currentProject.Properties.Item("FullPath").Value.ToString();

                if (entitiesDir.Length != 0)
                {
                    string[] dirs = entitiesDir.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    nameSpaceStr = $"{nameSpaceStr}.{string.Join(".", dirs)}";
                    path         = Path.Combine(path, string.Join("\\", dirs));
                }

                var entities = GetCheckedItems(this.addedList);
                var views    = GetCheckedItems(this.newList);
                entities.AddRange(views);

                foreach (var entity in entities)
                {
                    var    className = entity.GetPascalName(_template.ClassNameFormatting);
                    var    file      = Path.Combine(path, className + ".cs");
                    var    columns   = structure.GetColumns(entity);
                    string comment   = structure.GetComment(entity);
                    var    enums     = columns.Where(w => w.hasEnum).Select(s => s.getColumnEnum).ToList();

                    var content = RefreshService.GetContent(_template.text, nameSpaceStr, entity, className, columns, comment, enumLists: enums);

                    RefreshService.AddOrUpdate(file, content);
                    _targetProjectItems.AddFromFile(file);
                }
                MessageBox.Show("OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #23
0
        /// <summary>
        /// Ensures a link on a file is created in a project
        /// </summary>
        /// <param name="store">Store containing a model</param>
        /// <param name="uniqueProjectName">Unique project name of the project to which to add a link a a file</param>
        /// <param name="relativePathOfFileToCreate">Relative path to the link to create in the project described by <paramref name="relativePathOfFileToCreate"/></param>
        /// <param name="originalFileToLink">Path to the original file to link</param>
        public static void EnsureFileLinkInProject(Store store, string uniqueProjectName, string relativePathOfFileToCreate, string originalFileToLink)
        {
            Contract.Requires(store != null);
            Contract.Requires(relativePathOfFileToCreate != null);
            Contract.Requires(originalFileToLink != null);

            Project project = Store2DTE.GetProjectForStore(store);

            if (!string.IsNullOrWhiteSpace(uniqueProjectName))
            {
                project = project.DTE.Solution.Projects.OfType <Project>().FirstOrDefault(p => p.UniqueName == uniqueProjectName);
            }
            if (project == null)
            {
                return;
            }

            string[] pathSegments = relativePathOfFileToCreate.Split('\\');

            ProjectItems parent = project.ProjectItems;

            // Find the folder (or create it if necessary)
            for (int i = 0; i < pathSegments.Length - 1; ++i)
            {
                ProjectItem folder = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[i]);
                if (folder == null)
                {
                    folder = parent.AddFolder(pathSegments[i]);
                }

                parent = folder.ProjectItems;
            }

            // Find the file and create a link on the originalFileToLink it if necessary
            ProjectItem file = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[pathSegments.Length - 1]);

            if (file == null)
            {
                parent.AddFromFile(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(project.FullName), originalFileToLink)));
            }
        }
コード例 #24
0
        private void LinkAllFiles(ProjectItems sourceItems, ProjectItems targetItems)
        {
            Dictionary <string, string> targetNames = new Dictionary <string, string>();

            foreach (ProjectItem item in targetItems)
            {
                targetNames.Add(item.Name, item.Name);
            }

            foreach (ProjectItem item in sourceItems)
            {
                if (targetNames.ContainsKey(item.Name))
                {
                    // do nothing
                }
                else if (item.Kind == Constants.vsProjectItemKindPhysicalFolder)
                {
                    try
                    {
                        ProjectItem targetItem = targetItems.AddFolder(item.Name);
                        LinkAllFiles(item.ProjectItems, targetItem.ProjectItems);
                    }
                    catch (COMException comEx)
                    {
                        if (comEx.ErrorCode == -2147467259) //HRESULT 0x80004005
                        {
                            ProjectItem targetItem = IncludeExistingFolder(item.Name, targetItems);
                            LinkAllFiles(item.ProjectItems, targetItem.ProjectItems);
                        }
                    }
                }
                else if (item.Kind == Constants.vsProjectItemKindPhysicalFile)
                {
                    for (short i = 0; i < item.FileCount; i++)
                    {
                        targetItems.AddFromFile(item.get_FileNames(i));
                    }
                }
            }
        }
コード例 #25
0
        /// <summary>
        /// The method that creates a new item from the intput string.
        /// </summary>
        public override void Execute()
        {
            List <ProjectItem> items = new List <ProjectItem>();

            ProjectItems tempProjectItems = null;

            if (projectItem != null)
            {
                tempProjectItems = projectItem.ProjectItems;
            }
            else
            {
                tempProjectItems = targetProject.ProjectItems;
            }

            foreach (string fileName in Directory.GetFiles(sourceFilePath, searchPattern))
            {
                ProjectItem outputProjectItem;
                if (this.copy)
                {
                    outputProjectItem = tempProjectItems.AddFromFileCopy(fileName);
                }
                else
                {
                    outputProjectItem = tempProjectItems.AddFromFile(fileName);
                }

                items.Add(outputProjectItem);

                if (open && outputProjectItem != null)
                {
                    Window wnd = outputProjectItem.Open(Constants.vsViewKindPrimary);
                    wnd.Visible = true;
                    wnd.Activate();
                }
            }

            projectItems = items.ToArray();
        }
コード例 #26
0
        private bool ProcessDownloadedSolution(DirectoryInfo extractedFolder, string baseFolder, ProjectItems projectItems)
        {
            bool itemChanged = false;

            //Handle file adds
            foreach (FileInfo file in extractedFolder.GetFiles())
            {
                if (File.Exists(baseFolder + "\\" + file.Name))
                {
                    if (FileEquals(baseFolder + "\\" + file.Name, file.FullName))
                    {
                        continue;
                    }
                }

                File.Copy(file.FullName, baseFolder + "\\" + file.Name, true);
                projectItems.AddFromFile(baseFolder + "\\" + file.Name);
                itemChanged = true;
            }

            //Handle folder adds
            foreach (DirectoryInfo folder in extractedFolder.GetDirectories())
            {
                if (!Directory.Exists(baseFolder + "\\" + folder.Name))
                {
                    Directory.CreateDirectory(baseFolder + "\\" + folder.Name);
                }

                var  newProjectItems = projectItems;
                bool subItemChanged  = ProcessDownloadedSolution(folder, baseFolder + "\\" + folder.Name, newProjectItems);
                if (subItemChanged)
                {
                    itemChanged = true;
                }
            }

            return(itemChanged);
        }
コード例 #27
0
        public void FileAddedToSource(string file)
        {
            ProjectItem addedFile = GetProjectItemForPath(SourceProject.ProjectItems, file);

            if (addedFile != null)
            {
                string relativePath = GetPathRelativeToProject(addedFile);

                if (_projectItemsFilter.CanBeSynchronized(relativePath))
                {
                    ProjectItems targetCollection = LocateOrCreateCollection(TargetProject.ProjectItems,
                                                                             Path.GetDirectoryName(relativePath), true);

                    if (targetCollection != null)
                    {
                        try
                        {
                            targetCollection.AddFromFile(file);
                            _logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.FileSuccessfullyLinked,
                                                      relativePath, TargetProject.Name));
                        }
                        catch (COMException comEx)
                        {
                            if (comEx.ErrorCode == -2147467259) //HRESULT 0x80004005
                            {
                                _logger.Log(string.Format(CultureInfo.CurrentCulture,
                                                          Resources.FileAlreadyExistsInFileSystem, relativePath,
                                                          TargetProject.Name));
                            }
                        }
                    }
                }
                else
                {
                    _logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ItemExcludedByFilter, file, TargetProject.Name));
                }
            }
        }
コード例 #28
0
        private static bool ProcessDownloadedSolution(DirectoryInfo extractedFolder, string baseFolder, ProjectItems projectItems)
        {
            var itemChanged = false;

            //Handle file adds
            foreach (var file in extractedFolder.GetFiles())
            {
                if (File.Exists(Path.Combine(baseFolder, file.Name)))
                {
                    if (FileSystem.FileEquals(Path.Combine(baseFolder, file.Name), file.FullName))
                    {
                        continue;
                    }
                }

                File.Copy(file.FullName, Path.Combine(baseFolder, file.Name), true);
                projectItems.AddFromFile(Path.Combine(baseFolder, file.Name));
                itemChanged = true;
            }

            //Handle folder adds
            foreach (var folder in extractedFolder.GetDirectories())
            {
                if (!Directory.Exists(Path.Combine(baseFolder, folder.Name)))
                {
                    Directory.CreateDirectory(Path.Combine(baseFolder, folder.Name));
                }

                var newProjectItems = projectItems;
                var subItemChanged  = ProcessDownloadedSolution(folder, Path.Combine(baseFolder, folder.Name), newProjectItems);
                if (subItemChanged)
                {
                    itemChanged = true;
                }
            }

            return(itemChanged);
        }
コード例 #29
0
        private static void IncludeFiles(DirectoryInfo folder, ProjectItems items, bool isSolutionFolder, string folderKind, string recursiveFolderName)
        {
            dte.StatusBar.Text = $"Creating Folder {recursiveFolderName}";

            foreach (var item in folder.GetFileSystemInfos())
            {
                if (item is FileInfo)
                {
                    try
                    {
                        dte.StatusBar.Text = $"Adding file: {item.FullName}";
                        items.AddFromFile(item.FullName);
                    }
                    catch (Exception)
                    {
                        throw new Exception($"Cannot add file: {item.FullName}");
                    }
                }
                else if (item is DirectoryInfo info)
                {
                    if (isSolutionFolder)
                    {
                        var solutionFolder    = (SolutionFolder)((Project)items.Parent).Object;
                        var newSolutionFolder = solutionFolder.AddSolutionFolder(item.Name).ProjectItems;
                        IncludeFiles(info, newSolutionFolder, isSolutionFolder, folderKind, recursiveFolderName + @"\" + item.Name);
                    }
                    else
                    {
                        var newItems = items.AddFolder(item.Name, folderKind).ProjectItems;
                        IncludeFiles(info, newItems, isSolutionFolder, folderKind, recursiveFolderName + @"\" + item.Name);
                    }
                }
            }

            dte.StatusBar.Text = $"Created Folder {recursiveFolderName}";
        }
コード例 #30
0
ファイル: TemplatesCopying.cs プロジェクト: kouweizhong/waqs
        public static void CopyTemplates(DTE dte, string templatesFolderName, string netVersion, string toolsPath, string vsVersion, out string templatesFolder, out HashSet <string> existingTTIncludes, out ProjectItems templatesProjectItems)
        {
            var slnFolder = Path.GetDirectoryName(dte.Solution.FullName);

            templatesFolder = Path.Combine(slnFolder, templatesFolderName);
            if (!Directory.Exists(templatesFolder))
            {
                Directory.CreateDirectory(templatesFolder);
            }

            const string    solutionItemsFolderName         = "Solution Items";
            Project         solutionItems                   = dte.Solution.Projects.OfType <Project>().FirstOrDefault(pi => pi.Name == solutionItemsFolderName);
            UIHierarchyItem solutionItemsUIHierarchyItem    = null;
            Action          setSolutionItemsUIHierarchyItem = () => solutionItemsUIHierarchyItem = (dte.Windows.Cast <Window>().First(w => w.Type == vsWindowType.vsWindowTypeSolutionExplorer).Object as UIHierarchy)?.UIHierarchyItems.Cast <UIHierarchyItem>().First().UIHierarchyItems.Cast <UIHierarchyItem>().First(uihi => uihi.Name == solutionItemsFolderName);
            bool            solutionItemsExpanded;

            Project         templates = null;
            UIHierarchyItem templatesUIHierarchyItem    = null;
            Action          setTemplatesUIHierarchyItem = () => templatesUIHierarchyItem = solutionItemsUIHierarchyItem.UIHierarchyItems.Cast <UIHierarchyItem>().First(uihi => uihi.Name == templatesFolderName);
            bool            templatesItemsExpanded      = false;
            Action          addTemplatesUIHierarchyItem = () =>
            {
                templates = ((EnvDTE80.SolutionFolder)solutionItems.Object).AddSolutionFolder(templatesFolderName);
                setTemplatesUIHierarchyItem();
                templatesItemsExpanded = false;
            };

            if (solutionItems == null)
            {
                solutionItems = ((EnvDTE80.Solution2)dte.Solution).AddSolutionFolder(solutionItemsFolderName);
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = false;
                addTemplatesUIHierarchyItem();
            }
            else
            {
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded;

                templates = ((IEnumerable)solutionItems.ProjectItems).Cast <ProjectItem>().FirstOrDefault(pi => pi.Name == templatesFolderName).SubProject;
                if (templates == null)
                {
                    addTemplatesUIHierarchyItem();
                }
                else
                {
                    setTemplatesUIHierarchyItem();
                    templatesItemsExpanded = templatesUIHierarchyItem.UIHierarchyItems.Expanded;
                }
            }

            var ttincludesFolder = Path.Combine(toolsPath, "ttincludes");

            templatesProjectItems = (ProjectItems)templates.ProjectItems;
            existingTTIncludes    = new HashSet <string>(templatesProjectItems.Cast <ProjectItem>().Select(pi => pi.Name));
            string ttIncludeName = null;

            foreach (var ttInclude in Directory.GetFiles(ttincludesFolder).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            var ttIncludesFolderVS = Path.Combine(ttincludesFolder, vsVersion);

            foreach (var ttInclude in Directory.GetFiles(ttIncludesFolderVS).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            const string mergeTTIncludeFileName = "MergeT4Files.ttinclude";

            File.Copy(Path.Combine(ttincludesFolder, mergeTTIncludeFileName), Path.Combine(templatesFolder, mergeTTIncludeFileName), true);
            var specialMergeFolder = Path.Combine(ttincludesFolder, "SpecialMerge");

            foreach (var specialMerge in Directory.GetFiles(specialMergeFolder))
            {
                var ttSpecialMergeFileName = Path.GetFileName(specialMerge);
                var specialMergeFile       = Path.Combine(specialMergeFolder, ttSpecialMergeFileName);
                var ttSpecialMergeFileCopy = Path.Combine(templatesFolder, ttSpecialMergeFileName);
                File.Copy(specialMergeFile, ttSpecialMergeFileCopy, true);
                if (!existingTTIncludes.Contains(ttSpecialMergeFileName))
                {
                    templatesProjectItems.AddFromFile(ttSpecialMergeFileCopy);
                }
            }
            try
            {
                templatesUIHierarchyItem.UIHierarchyItems.Expanded     = templatesItemsExpanded;
                solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded = solutionItemsExpanded;
            }
            catch
            {
            }
            MergeTTIncludes(dte, templates, templatesFolder);
        }
コード例 #31
0
        internal static ProjectItem AddFromFile(ProjectItems projectItems, string filename)
        {
            ProjectItem pitem = projectItems.AddFromFile(filename);

            try
            {
                Helpers.CheckSharePointReferences(pitem);
                //Helpers.LogMessage(projectItems.DTE, projectItems.DTE, filename + ": File Added");
           }
            catch (Exception)
            {
            }

            return pitem;
        }
コード例 #32
0
ファイル: ReportViewer.cs プロジェクト: cjheath/NORMA
		private static void AddFileToProject(ProjectItems items, string filePath, string subDirectories, string fileText)
		{
			//ProjectItem destination = items.Item(0);
			string[] directories = subDirectories.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int depth = directories.Length;
			for (int i = 0; i < depth && items != null; ++i)
			{
				// This assumes the directory is there. If it is not, then
				// the guidelines for creating test libraries were not followed
				string directoryName = directories[i];
				ProjectItems nextItems = null;
				foreach (ProjectItem testItem in items)
				{
					if (testItem.Name == directoryName)
					{
						nextItems = testItem.ProjectItems;
						break;
					}
				}
				items = nextItems;
			}
			if (items != null)
			{
				File.WriteAllText(filePath, fileText, Encoding.UTF8);
				ProjectItem newItem = items.AddFromFile(filePath);
				SetFileProperties(newItem);
			}
		}
コード例 #33
0
 protected override void AddFileToContainer(string fullPath, ProjectItems container)
 {
     container.AddFromFile(fullPath);
 }
コード例 #34
0
 protected override void AddFileToContainer(string fullPath, ProjectItems container)
 {
     container.AddFromFile(fullPath);
 }
コード例 #35
0
        private bool ProcessDownloadedSolution(DirectoryInfo extractedFolder, string baseFolder, ProjectItems projectItems)
        {
            bool itemChanged = false;

            //Handle file adds
            foreach (FileInfo file in extractedFolder.GetFiles())
            {
                if (File.Exists(baseFolder + "\\" + file.Name))
                {
                    if (FileEquals(baseFolder + "\\" + file.Name, file.FullName))
                        continue;
                }

                File.Copy(file.FullName, baseFolder + "\\" + file.Name, true);
                projectItems.AddFromFile(baseFolder + "\\" + file.Name);
                itemChanged = true;
            }

            //Handle folder adds
            foreach (DirectoryInfo folder in extractedFolder.GetDirectories())
            {
                if (!Directory.Exists(baseFolder + "\\" + folder.Name))
                    Directory.CreateDirectory(baseFolder + "\\" + folder.Name);

                var newProjectItems = projectItems;
                bool subItemChanged = ProcessDownloadedSolution(folder, baseFolder + "\\" + folder.Name, newProjectItems);
                if (subItemChanged)
                    itemChanged = true;
            }

            return itemChanged;
        }
コード例 #36
0
 private static void AddFromProjectFilePath(Project project, ProjectItems items, NewItemDynamicParameters p)
 {
     items.AddFromFile(p.ProjectFilePath);
 }
コード例 #37
0
ファイル: Linker.cs プロジェクト: GeertvanHorrik/Caitlyn
        /// <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);
        }
コード例 #38
0
        /// <summary>
        /// Copy a file to a project relative path.
        /// </summary>
        /// <param name="projectHierarchy">
        /// The project where to add the file.
        /// </param>
        /// <param name="fileName">
        /// The path to the file to copy.
        /// </param>
        /// <param name="targetPath">
        /// The target path, including the filename.
        /// </param>
        /// <param name="addFileOptions">
        /// The options to use while coping the file.
        /// </param>
        private async Task AddFileToProjectInFolder(IVsHierarchy projectHierarchy, string fileName, string targetPath, AddFileOptions addFileOptions)
        {
            targetPath = AzureIoTHubConnectedServiceHandlerHelper.GetProjectRelativePath(projectHierarchy, targetPath);
            Project      project = ConnectedServicesUtilities.GetDteProject(projectHierarchy);
            ProjectItems items   = project.ProjectItems;

            fileName = await this.CopyFileAsync(fileName, targetPath);

            string fileToAdd      = ConnectedServicesUtilities.GetProjectFullPath(projectHierarchy, targetPath);
            string targetFileName = Path.GetFileName(fileToAdd);

            // Build the directory structure if it doesn't already exist.
            Directory.CreateDirectory(Path.GetDirectoryName(fileToAdd));

            // clone the AdditionalReplacementValues dictionary so we aren't modifying the original
            Dictionary <string, string> replacementValues = new Dictionary <string, string>(addFileOptions.AdditionalReplacementValues);

            ProjectItem item        = AzureIoTHubConnectedServiceHandlerHelper.GetNestedProjectItem(items, targetPath);
            bool        existOnDisk = File.Exists(fileToAdd);

            if (item == null &&
                existOnDisk)
            {
                // The file is not in the project. We should add the file.
                // This is some arbitrary file, which we'll update in the same
                // path as existing project files.
                // This is 'fileToAdd' because we're not adding the final file here.
                item = items.AddFromFile(fileToAdd);
            }

            if (item != null)
            {
                // Add the folder-specific RootNamespace replacement value so $RootNamespace$ has the folder structure in it for C# projects
                this.AddRootNamespaceReplacementValue(replacementValues, item.Collection);

                bool filesEqual = this.AreFilesEqualWithReplacement(item, fileName, replacementValues);

                if (!filesEqual)
                {
                    if (!addFileOptions.SuppressOverwritePrompt && !this.PromptOverwrite(targetFileName))
                    {
                        // The user chose not to overwrite the file, so abort adding this file.
                        return;
                    }

                    // Get the document and overwrite with file content.
                    BufferUtilities.UpdateProjectItemFromFile(item, fileName);
                }
            }
            else
            {
                File.Copy(fileName, fileToAdd);
                item = items.AddFromFile(fileToAdd);

                // Add the folder-specific RootNamespace replacement value so $RootNamespace$ has the folder structure in it for C# projects
                this.AddRootNamespaceReplacementValue(replacementValues, item.Collection);
            }

            this.PerformTokenReplacement(item, replacementValues);

            if (addFileOptions.OpenOnComplete && !item.IsOpen)
            {
                try
                {
                    var window = item.Open();

                    // Ensure that the window is always shown regardless of "Preview"
                    // user settings.
                    if (window != null &&
                        !window.Visible)
                    {
                        window.Visible = true;
                    }
                }
                catch (Exception)
                {
                }
            }
        }
コード例 #39
0
ファイル: IntegrationTest.cs プロジェクト: icool123/T4Toolbox
        protected static ProjectItem CreateTestProjectItemFromFile(ProjectItems projectItems, string fileName)
        {
            if (projectItems == null)
            {
                throw new ArgumentNullException("projectItems");
            }

            if (!File.Exists(fileName))
            {
                File.WriteAllText(fileName, string.Empty);                
            }

            return projectItems.AddFromFile(fileName);
        }
コード例 #40
0
 private void duplicateFiles(ProjectItems projItems)
 {
     ProjectItem projItem;
     for (int i = 1; i <= projItems.Count; i++)
     {
         projItem = projItems.Item(i);
         Debug.Write(projItem.Name + "  " + projItem.Kind);
         try
         {
             if (projItem.ProjectItems.Count > 0)
             {
                 duplicateFiles(projItem.ProjectItems);
             }
             else if (selectedProjectItems.Contains(projItem))
             {
                 selectedProjectItems.Remove(projItem);
                 String newPath = copyFile(projItem);
                 if (newPath != null)
                 {
                     try
                     {
                         lastAdded = projItems.AddFromFile(newPath);
                     }
                     catch (Exception) { }
                 }
             }
         }
         catch (Exception)
         {
         }
     }
 }
コード例 #41
0
ファイル: ModelSharpTool.cs プロジェクト: pescuma/modelsharp
		private void AddFromFileWithFolders(ProjectItems root, string name, string dir)
		{
			string pathToNow = null;
			var tmp = name.Split('\\');
			for (int i = 0; i < tmp.Length - 1; i++)
			{
				string thisDir = tmp[i];
				pathToNow = pathToNow == null ? thisDir : Path.Combine(pathToNow, thisDir);

				var item = Find(root, thisDir);
				if (item == null)
				{
					//AddExistingFolder(root.ContainingProject, pathToNow);

					//item = Find(root, thisDir);
					//if (item == null)
					item = root.AddFolder(thisDir);
				}

				root = item.ProjectItems;
			}

			if (Find(root, tmp[tmp.Length - 1]) == null)
				root.AddFromFile(Path.Combine(dir, name));
		}
コード例 #42
0
ファイル: MainPackage.cs プロジェクト: Orchidsoft/vs-net-dte
        private static void ProcessCssFile(ProjectItems parent, string cssPath)
        {
            var sassPath = $"{Path.Combine(Path.GetDirectoryName(cssPath), Path.GetFileNameWithoutExtension(cssPath))}.scss";
            var sassProjectItem = AssetCache.Lookup(sassPath);

            try
            {
                if (sassProjectItem != null)
                    parent = sassProjectItem.ProjectItems;

                parent.AddFromFile(cssPath);
            }
            catch (Exception e)
            {
                Logger.WriteLine("Exception encountered when trying to add a file to the project");
                Logger.WriteLine(e.Message);
                Logger.WriteLine("Stack trace:");
                Logger.WriteLine(e.StackTrace);
            }
        }
コード例 #43
0
ファイル: MainPackage.cs プロジェクト: matt40k/vs-net-dte
        private static void ProcessCssFile(ProjectItems parent, string cssPath)
        {
            var sassPath = $"{Path.Combine(Path.GetDirectoryName(cssPath), Path.GetFileNameWithoutExtension(cssPath))}.scss";
            var sassProjectItem = AssetCache.Lookup(sassPath);

            if (sassProjectItem != null)
                parent = sassProjectItem.ProjectItems;

            parent.AddFromFile(cssPath);
        }
コード例 #44
0
 internal ProjectItem AddFromFile(ProjectItems projectItems, string filename)
 {
   return projectItems.AddFromFile(filename);
 }
コード例 #45
0
ファイル: TemplatesCopying.cs プロジェクト: bnjMichel/waqs
        public static void CopyTemplates(DTE dte, string templatesFolderName, string netVersion, string toolsPath, string vsVersion, out string templatesFolder, out HashSet<string> existingTTIncludes, out ProjectItems templatesProjectItems)
        {
            var slnFolder = Path.GetDirectoryName(dte.Solution.FullName);
            templatesFolder = Path.Combine(slnFolder, templatesFolderName);
            if (!Directory.Exists(templatesFolder))
            {
                Directory.CreateDirectory(templatesFolder);
            }

            const string solutionItemsFolderName = "Solution Items";
            Project solutionItems = dte.Solution.Projects.OfType<Project>().FirstOrDefault(pi => pi.Name == solutionItemsFolderName);
            UIHierarchyItem solutionItemsUIHierarchyItem = null;
            Action setSolutionItemsUIHierarchyItem = () => solutionItemsUIHierarchyItem = (dte.Windows.Cast<Window>().First(w => w.Type == vsWindowType.vsWindowTypeSolutionExplorer).Object as UIHierarchy)?.UIHierarchyItems.Cast<UIHierarchyItem>().First().UIHierarchyItems.Cast<UIHierarchyItem>().First(uihi => uihi.Name == solutionItemsFolderName);
            bool solutionItemsExpanded;

            Project templates = null;
            UIHierarchyItem templatesUIHierarchyItem = null;
            Action setTemplatesUIHierarchyItem = () => templatesUIHierarchyItem = solutionItemsUIHierarchyItem.UIHierarchyItems.Cast<UIHierarchyItem>().First(uihi => uihi.Name == templatesFolderName);
            bool templatesItemsExpanded = false;
            Action addTemplatesUIHierarchyItem = () =>
            {
                templates = ((EnvDTE80.SolutionFolder)solutionItems.Object).AddSolutionFolder(templatesFolderName);
                setTemplatesUIHierarchyItem();
                templatesItemsExpanded = false;
            };

            if (solutionItems == null)
            {
                solutionItems = ((EnvDTE80.Solution2)dte.Solution).AddSolutionFolder(solutionItemsFolderName);
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = false;
                addTemplatesUIHierarchyItem();
            }
            else
            {
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded;

                templates = ((IEnumerable)solutionItems.ProjectItems).Cast<ProjectItem>().FirstOrDefault(pi => pi.Name == templatesFolderName).SubProject;
                if (templates == null)
                {
                    addTemplatesUIHierarchyItem();
                }
                else
                {
                    setTemplatesUIHierarchyItem();
                    templatesItemsExpanded = templatesUIHierarchyItem.UIHierarchyItems.Expanded;
                }
            }

            var ttincludesFolder = Path.Combine(toolsPath, "ttincludes");
            templatesProjectItems = (ProjectItems)templates.ProjectItems;
            existingTTIncludes = new HashSet<string>(templatesProjectItems.Cast<ProjectItem>().Select(pi => pi.Name));
            string ttIncludeName = null;
            foreach (var ttInclude in Directory.GetFiles(ttincludesFolder).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            var ttIncludesFolderVS = Path.Combine(ttincludesFolder, vsVersion);
            foreach (var ttInclude in Directory.GetFiles(ttIncludesFolderVS).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            const string mergeTTIncludeFileName = "MergeT4Files.ttinclude";
            File.Copy(Path.Combine(ttincludesFolder, mergeTTIncludeFileName), Path.Combine(templatesFolder, mergeTTIncludeFileName), true);
            var specialMergeFolder = Path.Combine(ttincludesFolder, "SpecialMerge");
            foreach (var specialMerge in Directory.GetFiles(specialMergeFolder))
            {
                var ttSpecialMergeFileName = Path.GetFileName(specialMerge);
                var specialMergeFile = Path.Combine(specialMergeFolder, ttSpecialMergeFileName);
                var ttSpecialMergeFileCopy = Path.Combine(templatesFolder, ttSpecialMergeFileName);
                File.Copy(specialMergeFile, ttSpecialMergeFileCopy, true);
                if (!existingTTIncludes.Contains(ttSpecialMergeFileName))
                {
                    templatesProjectItems.AddFromFile(ttSpecialMergeFileCopy);
                }
            }
            try
            {
                templatesUIHierarchyItem.UIHierarchyItems.Expanded = templatesItemsExpanded;
                solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded = solutionItemsExpanded;
            }
            catch
            {
            }
            MergeTTIncludes(dte, templates, templatesFolder);
        }
コード例 #46
0
 internal ProjectItem AddFromFile(ProjectItems projectItems, string filename)
 {
     return(projectItems.AddFromFile(filename));
 }