예제 #1
0
        public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
        {
            ProjectItemTypes type = GetProjectItemType(projectItem);
            switch (type)
            {
                case ProjectItemTypes.Parent:
                    this.parentProjectItem = projectItem;
                    break;
                case ProjectItemTypes.Child:
                    this.childrenProjectItems.Add(projectItem);
                    break;
            }

            projectItem.Properties.Item("CopyToOutputDirectory").Value = 1;
        }
 public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
 {
     try
     {
         if (projectItem.Name.Substring(projectItem.Name.Length - 3, 3) == "dal")
         {
             this.dal = projectItem;
         }
         else
         {
             this.template = projectItem;
         }
     }
     catch (Exception e)
     {
         canAdd = false;
     }
 }
        private void AddSubFolderInProject(Project project, ProjectItem vsProjectItem)
        {
            var newFolder = new FolderProxy(vsProjectItem.Name, project);
            newFolder.VsProjectItem = vsProjectItem;
            newFolder.DirectoryPath = new System.IO.DirectoryInfo(vsProjectItem.get_FileNames(0)).FullName;

            project.Items.Add(newFolder);

            if (vsProjectItem.ProjectItems.Count > 0)
            {
                AddFilesAndFolders(newFolder, vsProjectItem);
            }
        }
        private void AddFilesAndFolders(Folder parentFolder, ProjectItem parentVsItem)
        {
            for (int x = 1; x <= parentVsItem.ProjectItems.Count; x++)
            {
                var vsItem = parentVsItem.ProjectItems.Item(x);
                if (vsItem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)
                {
                    var newFolder = new FolderProxy(vsItem.Name, parentFolder);
                    newFolder.VsProjectItem = vsItem;
                    newFolder.DirectoryPath = new System.IO.DirectoryInfo(vsItem.get_FileNames(0)).FullName;

                    parentFolder.Items.Add(newFolder);

                    if (vsItem.ProjectItems.Count > 0)
                        AddFilesAndFolders(newFolder, vsItem);
                }
                else if (vsItem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
                {
                    var newFile = AddFileToFolder(parentFolder, vsItem);
                }
            }
        }
예제 #5
0
        public void TestAutomationOnProjectItems()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the global service provider and the dte
                IServiceProvider sp = VsIdeTestHostContext.ServiceProvider;
                DTE dte             = (DTE)sp.GetService(typeof(DTE));

                string destination = Path.Combine(TestContext.TestDir, TestContext.TestName);
                Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true);

                OAProject automation = Utilities.FindExtObject(sp, Utilities.NestedProjectGuid, TestContext.TestName) as OAProject;
                Assert.IsNotNull(automation, "Failed to create a project using automation");

                string newModelFilePath = TestUtils.GetNewFileName(TestContext.TestDir, TestContext.TestName, "model");
                EnvDTE.ProjectItem pi   = automation.ProjectItems.AddFromFileCopy(Path.GetFullPath(newModelFilePath));
                Assert.IsNotNull(pi, "Failed to create a modeling project item through automation");
                Assert.IsTrue(pi.Name == Path.GetFileName(newModelFilePath), "ProjectItems AddFromFileCopy has not returned the item that was added");

                bool[] found = new bool[3];
                // Test enumerators on project items
                foreach (EnvDTE.ProjectItem item in automation.ProjectItems)
                {
                    if (item.Name == Path.GetFileName(newModelFilePath))
                    {
                        found[0] = true;
                    }
                    else if (item.Name == "Program.cs")
                    {
                        found[1] = true;
                    }
                    else if (item.Name == "AssemblyInfo.cs")
                    {
                        found[2] = true;
                    }
                }

                foreach (bool foundValue in found)
                {
                    Assert.IsTrue(foundValue, "The iterator on item collection has not been implemented correctly");
                }

                /*****Test the AddFolder method*****/
                //Add a simple folder to the project
                ProjectItem folder = automation.ProjectItems.AddFolder("directory", null);
                //Add a subfolder to the folder
                ProjectItem subfolder = folder.ProjectItems.AddFolder("subdirectory", string.Empty);
                //Add another subfolder to that folder
                subfolder.ProjectItems.AddFolder("subsubdirectory", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);

                //Verify that we have the following structure:
                //Project
                //	-directory
                //		-subdirectory
                //			-subsubdirectory
                ProjectItem directory       = automation.ProjectItems.Item("directory") as ProjectItem;
                ProjectItem subdirectory    = directory.ProjectItems.Item("subdirectory") as ProjectItem;
                ProjectItem subsubdirectory = subdirectory.ProjectItems.Item("subsubdirectory") as ProjectItem;
                Assert.IsNotNull(directory);
                Assert.IsNotNull(subdirectory);
                Assert.IsNotNull(subsubdirectory);


                bool argumentExceptionThrown = false;
                try
                {
                    //We expect virtual folders to fail this way.
                    folder.ProjectItems.AddFolder("virtualfolder", EnvDTE.Constants.vsProjectItemKindVirtualFolder);
                }
                catch (ArgumentException) { argumentExceptionThrown = true; }
                Assert.IsTrue(argumentExceptionThrown);

                argumentExceptionThrown = false;
                try
                {
                    //Verify that you can't add a folder where a node with that name already exists
                    folder.ProjectItems.AddFolder("subdirectory", string.Empty);
                }
                catch (ArgumentException) { argumentExceptionThrown = true; }
                Assert.IsTrue(argumentExceptionThrown);
            });
        }
예제 #6
0
 void IWizard.ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #7
0
        /// <summary>
        /// Synchronizes the resource file properties.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="targetProjectType">Type of the target project.</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 SynchronizeResourceFileProperties(ProjectItem source, ProjectItem target, ProjectType targetProjectType)
        {
            Argument.IsNotNull("source", source);
            Argument.IsNotNull("target", target);

            Log.Debug("Synchronizing resource file properties for '{0}'", source.Name);

            target.Properties.Item("CustomTool").Value = source.Properties.Item("CustomTool").Value;
            target.Properties.Item("CustomToolNamespace").Value = source.Properties.Item("CustomToolNamespace").Value;

            //var customToolOutput = (string)source.Properties.Item("CustomToolOutput").Value;
            //customToolOutput = customToolOutput.Replace(".Designer.cs", string.Format(".{0}.Designer.cs", targetProjectType.ToString()));
            //target.Properties.Item("CustomToolOutput").Value = customToolOutput;

            Log.Debug("Running custom tool to generate 'code-behind' file");

            try
            {
                // We need to run the custom tool first
                var vsProjectItem = (VSProjectItem)target.Object;
                vsProjectItem.RunCustomTool();
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to run custom tool");
            }

            Log.Debug("Ran custom tool to generate 'code-behind' file");

            // string customOutput = (string) source.Properties.Item("CustomToolOutput").Value;
            // customOutput = customOutput.Replace(".cs", string.Format(".{0}.cs", targetProjectType));
            // target.Properties.Item("CustomToolOutput").Value = customOutput;
            Log.Debug("Synchronized resource file properties", source.Name);
        }
예제 #8
0
        /// <summary>
        /// Handles the change of a project item.
        /// </summary>
        /// <param name="projectItem">The project item.</param>
        /// <param name="action">The action that happened to the project item.</param>
        /// <param name="oldName">The old name in case of a rename, can be <c>null</c>.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">action</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="projectItem" /> is <c>null</c>.</exception>
        /// <exception cref="InvalidOperationException">The root project file does not exist.</exception>
        /// <exception cref="ArgumentException">The <paramref name="oldName" /> is <c>null</c> or whitespace but the action is <see cref="ProjectItemAction.Rename" />.</exception>
        public void HandleProjectItemChange(ProjectItem projectItem, ProjectItemAction action, string oldName = null)
        {
            Argument.IsNotNull("projectItem", projectItem);
            if (action == ProjectItemAction.Rename)
            {
                Argument.IsNotNullOrWhitespace("oldName", oldName);
            }

            Log.Debug("Linking {0} projects to {1}", TargetProjects.Length, RootProject.Name);

            var sourceProjectItems = projectItem.Collection;
            var fileFilter = new List<string>(new[] { projectItem.GetNameRelativeToRoot() });
            if (!string.IsNullOrWhiteSpace(oldName))
            {
                // Handle delete of old item
                var relativeName = projectItem.GetNameRelativeToRoot();
                var relativeNameWithoutFile = relativeName.Substring(0, relativeName.Length - projectItem.Name.Length);

                var oldRelativeName = Path.Combine(relativeNameWithoutFile, oldName);
                fileFilter.Add(oldRelativeName);
            }

            foreach (var targetProject in TargetProjects)
            {
                Log.Debug("Linking project {0}", targetProject.Name);

                var targetProjectItems = GetTargetProjectItems(sourceProjectItems, targetProject);

                switch (action)
                {
                    case ProjectItemAction.Add:
                        AddFilesAndFolders(sourceProjectItems, targetProjectItems, targetProject.GetProjectType(), 1, fileFilter);
                        break;

                    case ProjectItemAction.Rename:
                        RemoveFilesAndFolders(sourceProjectItems, targetProjectItems, targetProject.GetProjectType(), 1, fileFilter);
                        AddFilesAndFolders(sourceProjectItems, targetProjectItems, targetProject.GetProjectType(), 1, fileFilter);
                        break;

                    case ProjectItemAction.Remove:
                        RemoveFilesAndFolders(sourceProjectItems, targetProjectItems, targetProject.GetProjectType(), 1, fileFilter);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("action");
                }

                Log.Debug("Linked project");
            }

            Log.Debug("Linked {0} projects", TargetProjects.Length);
        }
예제 #9
0
 public ProjectItem(EnvDTE.ProjectItem dteProjectItem)
 {
     _dteProjectItem = dteProjectItem;
 }
예제 #10
0
        public static bool TryGetFolder(this ProjectItems projectItems, string name, out ProjectItem projectItem)
        {
            projectItem = GetProjectItem(projectItems, name, VsConstants.VsProjectItemKindPhysicalFolder);

            return(projectItem != null);
        }
 /// <summary>
 /// 保存XML信息
 /// </summary>
 /// <param name="entity"></param>
 public void SaveXML()
 {
     EntityMappingConfig.SaveXML(_fileName, _doc);
     EnvDTE.ProjectItem newit = DesignerInfo.CurrentProject.ProjectItems.AddFromFile(_fileName);
     newit.Properties.Item("BuildAction").Value = (int)BuildAction.Resource;
 }
예제 #12
0
 /// <summary>
 /// Implements <see cref="IWizard.ProjectItemFinishedGenerating"/>
 /// </summary>
 protected void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #13
0
 /// <summary>
 /// Implements <see cref="IWizard.BeforeOpeningFile"/>
 /// </summary>
 protected void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #14
0
        /// <summary>
        /// 创建Service类
        /// </summary>
        /// <param name="applicationStr">根命名空间</param>
        /// <param name="name">类名</param>
        /// <param name="dtoFolder">父文件夹</param>
        /// <param name="dirName">类所在文件夹目录</param>
        private void CreateServiceFile(string applicationStr, string name, string cnName, ProjectItem dtoFolder, string dirName, CodeClass codeClass)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var model = new ServiceFileModel()
            {
                Namespace = applicationStr, Name = name, CnName = cnName, DirName = dirName.Replace("\\", ".")
            };

            string content_IService  = Engine.Razor.RunCompile("IServiceTemplate", typeof(ServiceFileModel), model);
            string fileName_IService = $"I{name}AppService.cs";

            AddFileToProjectItem(dtoFolder, content_IService, fileName_IService);

            string content_Service  = Engine.Razor.RunCompile("ServiceTemplate", typeof(ServiceFileModel), model);
            string fileName_Service = $"{name}AppService.cs";

            AddFileToProjectItem(dtoFolder, content_Service, fileName_Service);
        }
예제 #15
0
        /// <summary>
        /// 创建AppAuthorizationProvider权限配置类
        /// </summary>
        /// <param name="applicationStr">根命名空间</param>
        /// <param name="name">类名</param>
        /// <param name="authorizationFolder">父文件夹</param>
        private void CreateAppAuthorizationProviderFile(string applicationStr, string name, string cnName, ProjectItem authorizationFolder)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var model = new AppAuthorizationProviderFileModel()
            {
                Namespace = applicationStr, Name = name, CnName = cnName
            };
            string content  = Engine.Razor.RunCompile("AppAuthorizationProviderTemplate", typeof(AppAuthorizationProviderFileModel), model);
            string fileName = name + "AuthorizationProvider.cs";

            AddFileToProjectItem(authorizationFolder, content, fileName);
        }
 /// <summary>Queries if this action supports the provided project item and its containing project</summary>
 /// <param name="item">Project item to query support for</param>
 /// <returns>True if the action is supported, false otherwise.</returns>
 public abstract bool QuerySupportForProject(EnvDTE.ProjectItem item);
예제 #17
0
 public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #18
0
            private StateRefreshChanges ToggleOnRequiredBranches(OutputFormatBranch formatBranch, int branchGeneratorIndex, bool testToggleOff)
            {
                StateRefreshChanges retVal = StateRefreshChanges.None;

                if (formatBranch.IsModifier)
                {
                    if (formatBranch.SelectedORMGenerator == null)
                    {
                        // The build item is associated primarily with the primary generator,
                        // not the modifier. We need to make sure that the primary generator
                        // is turned on.
                        IORMGenerator      modifierGenerator = formatBranch.ORMGenerators[0];
                        OutputFormatBranch primaryBranch     = _branches[modifierGenerator.ProvidesOutputFormat];
                        IORMGenerator      primaryGenerator  = primaryBranch.SelectedORMGenerator;
                        if (primaryGenerator == null)
                        {
                            if (StateRefreshChanges.None != ToggleOnRequiredBranches(primaryBranch, 0, false))
                            {
                                retVal = StateRefreshChanges.Entire;
                            }
                            primaryGenerator = primaryBranch.SelectedORMGenerator;
                            if (primaryGenerator == null)
                            {
                                return(StateRefreshChanges.None);
                            }
                        }
                        formatBranch.SelectedORMGenerator = modifierGenerator;
                        SetItemMetaData(_parent.BuildItemsByGenerator[primaryGenerator.OfficialName], ITEMMETADATA_ORMGENERATOR, primaryBranch.SelectedGeneratorOfficialNames);
                        retVal |= StateRefreshChanges.Children | StateRefreshChanges.Children;
                    }
                    else if (testToggleOff)
                    {
                        // Note that we can always remove a modifier, do not call CanRemoveGenerator
                        RemoveGenerator(formatBranch);
                        retVal |= StateRefreshChanges.Current | StateRefreshChanges.Children;
                    }
                }
                else if (formatBranch.SelectedORMGenerator == null)
                {
#if VISUALSTUDIO_10_0
                    string projectPath = Parent._project.FullPath;
#else
                    string projectPath = Parent._project.FullFileName;
#endif
                    EnvDTE.ProjectItem projectItem = Parent._projectItem;

                    string sourceFileName   = _parent._sourceFileName;
                    string projectItemPath  = (string)projectItem.Properties.Item("LocalPath").Value;
                    string newItemDirectory = (new Uri(projectPath)).MakeRelativeUri(new Uri(projectItemPath)).ToString();
                    newItemDirectory = Path.GetDirectoryName(newItemDirectory);

                    retVal = StateRefreshChanges.Current | StateRefreshChanges.Children;
                    IORMGenerator useGenerator   = formatBranch.ORMGenerators[branchGeneratorIndex];
                    string        outputFileName = useGenerator.GetOutputFileDefaultName(sourceFileName);
                    outputFileName = Path.Combine(newItemDirectory, outputFileName);
#if VISUALSTUDIO_10_0
                    ProjectItemElement newBuildItem;
#else
                    BuildItem newBuildItem;
#endif
                    newBuildItem = useGenerator.AddGeneratedFileItem(_parent._itemGroup, sourceFileName, outputFileName);                     //string.Concat(newItemPath, Path.DirectorySeparatorChar, _parent._sourceFileName));
                    _parent.BuildItemsByGenerator[useGenerator.OfficialName] = newBuildItem;
                    _parent.RemoveRemovedItem(newBuildItem);
                    formatBranch.SelectedORMGenerator = useGenerator;
                    IList <string> requiredFormats      = useGenerator.RequiresInputFormats;
                    int            requiredFormatCount  = requiredFormats.Count;
                    IList <string> companionFormats     = useGenerator.RequiresCompanionFormats;
                    int            companionFormatCount = companionFormats.Count;
                    int            totalCount           = requiredFormatCount + companionFormatCount;
                    for (int i = 0; i < totalCount; ++i)
                    {
                        OutputFormatBranch requiredBranch;
                        if (_branches.TryGetValue(i < requiredFormatCount ? requiredFormats[i] : companionFormats[i - requiredFormatCount], out requiredBranch))
                        {
                            if (StateRefreshChanges.None != ToggleOnRequiredBranches(requiredBranch, 0, false))
                            {
                                retVal = StateRefreshChanges.Entire;
                            }
                        }
                    }
                }
                else if (testToggleOff && CanRemoveGenerator(formatBranch))
                {
                    RemoveGenerator(formatBranch);
                    retVal = StateRefreshChanges.Current | StateRefreshChanges.Children;
                }
                return(retVal);
            }
 private Folder CreateFolderItem(ProjectItem projectItem)
 {
     return new Folder
                {
                    Name = projectItem.Name,
                    TargetFolderName = projectItem.Name,
                    Items = GetChildItems(projectItem.ProjectItems).ToArray()
                };
 }
예제 #20
0
        /// <summary>
        /// Creates a new project item from an existing item template file and adds it to the project.
        /// </summary>
        /// <param name="fileName">The full path and file name of the template project file.</param>
        /// <param name="name">The file name to use for the new project item.</param>
        /// <returns>A ProjectItem object. </returns>
        public override EnvDTE.ProjectItem AddFromTemplate(string fileName, string name)
        {
            return(UIThread.DoOnUIThread(delegate() {
                if (this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed)
                {
                    throw new InvalidOperationException();
                }

                ProjectNode proj = this.Project.Project;

                IVsExtensibility3 extensibility = this.Project.Project.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3;

                if (extensibility == null)
                {
                    throw new InvalidOperationException();
                }

                EnvDTE.ProjectItem itemAdded = null;
                extensibility.EnterAutomationFunction();

                try
                {
                    string fixedFileName = fileName;

                    if (!File.Exists(fileName))
                    {
                        string tempFileName = GetTemplateNoZip(fileName);
                        if (File.Exists(tempFileName))
                        {
                            fixedFileName = tempFileName;
                        }
                    }

                    // Determine the operation based on the extension of the filename.
                    // We should run the wizard only if the extension is vstemplate
                    // otherwise it's a clone operation
                    VSADDITEMOPERATION op;

                    if (Utilities.IsTemplateFile(fixedFileName))
                    {
                        op = VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD;
                    }
                    else
                    {
                        op = VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE;
                    }

                    VSADDRESULT[] result = new VSADDRESULT[1];

                    // It is not a very good idea to throw since the AddItem might return Cancel or Abort.
                    // The problem is that up in the call stack the wizard code does not check whether it has received a ProjectItem or not and will crash.
                    // The other problem is that we cannot get add wizard dialog back if a cancel or abort was returned because we throw and that code will never be executed. Typical catch 22.
                    ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, name, 0, new string[1] {
                        fixedFileName
                    }, IntPtr.Zero, result));

                    string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems);
                    string templateFilePath = System.IO.Path.Combine(fileDirectory, name);
                    itemAdded = this.EvaluateAddResult(result[0], templateFilePath);
                }
                finally
                {
                    extensibility.ExitAutomationFunction();
                }

                return itemAdded;
            }));
        }
예제 #21
0
        /// <summary>
        /// Determines whether the specified item should be skipped based on the rules in the configuration.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="targetProjectType">Type of the target project.</param>
        /// <returns><c>true</c> if the item should be skipped; otherwise <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="source" /> is <c>null</c>.</exception>
        private bool ShouldSkipAddingOfItem(ProjectItem source, ProjectType targetProjectType)
        {
            Argument.IsNotNull("source", source);

            var rootProjectConfiguration = GetRootProjectConfiguration(source.ContainingProject);

            return MatchesRule(source, rootProjectConfiguration, RuleType.DoNotAdd, targetProjectType);
        }
예제 #22
0
        /// <summary>
        /// // If we didn't find the project item at the top level, then we look one more level down.
        /// In VS files can have other nested files like foo.aspx and foo.aspx.cs or web.config and web.debug.config.
        /// These are actually top level files in the file system but are represented as nested project items in VS.
        /// </summary>
        private static bool TryGetFileNestedFile(ProjectItems projectItems, string name, out ProjectItem projectItem)
        {
            string parentFileName;

            if (!_knownNestedFiles.TryGetValue(name, out parentFileName))
            {
                parentFileName = Path.GetFileNameWithoutExtension(name);
            }

            // If it's not one of the known nested files then we're going to look up prefixes backwards
            // i.e. if we're looking for foo.aspx.cs then we look for foo.aspx then foo.aspx.cs as a nested file
            ProjectItem parentProjectItem = GetProjectItem(projectItems, parentFileName, _fileKinds);

            if (parentProjectItem != null)
            {
                // Now try to find the nested file
                projectItem = GetProjectItem(parentProjectItem.ProjectItems, name, _fileKinds);
            }
            else
            {
                projectItem = null;
            }

            return(projectItem != null);
        }
예제 #23
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 static void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            string message = "";

            if (_dte.SelectedItems.Count > 0)
            {
                SelectedItem selectedItem      = _dte.SelectedItems.Item(1);
                ProjectItem  selectProjectItem = selectedItem.ProjectItem;

                if (selectProjectItem != null)
                {
                    //前端工程源码目录
                    string frontBaseUrl = "";

                    #region 获取出基础信息
                    //获取当前点击的类所在的项目
                    Project topProject = selectProjectItem.ContainingProject;
                    //当前类在当前项目中的目录结构
                    string dirPath = GetSelectFileDirPath(topProject, selectProjectItem);

                    //当前类命名空间
                    string namespaceStr = selectProjectItem.FileCodeModel.CodeElements.OfType <CodeNamespace>().First().FullName;
                    //当前项目根命名空间
                    string applicationStr = "";
                    if (!string.IsNullOrEmpty(namespaceStr))
                    {
                        applicationStr = namespaceStr.Substring(0, namespaceStr.IndexOf("."));
                    }
                    //当前类
                    CodeClass codeClass = GetClass(selectProjectItem.FileCodeModel.CodeElements);
                    //当前项目类名
                    string className = codeClass.Name;
                    //当前类中文名 [Display(Name = "供应商")]
                    string classCnName = "";
                    //当前类说明 [Description("品牌信息")]
                    string classDescription = "";
                    //获取类的中文名称和说明
                    foreach (CodeAttribute classAttribute in codeClass.Attributes)
                    {
                        switch (classAttribute.Name)
                        {
                        case "Display":
                            if (!string.IsNullOrEmpty(classAttribute.Value))
                            {
                                string displayStr = classAttribute.Value.Trim();
                                foreach (var displayValueStr in displayStr.Split(','))
                                {
                                    if (!string.IsNullOrEmpty(displayValueStr))
                                    {
                                        if (displayValueStr.Split('=')[0].Trim() == "Name")
                                        {
                                            classCnName = displayValueStr.Split('=')[1].Trim().Replace("\"", "");
                                        }
                                    }
                                }
                            }
                            break;

                        case "Description":
                            classDescription = classAttribute.Value;
                            break;
                        }
                    }

                    //获取当前解决方案里面的项目列表
                    List <ProjectItem> solutionProjectItems = GetSolutionProjects(_dte.Solution);
                    #endregion

                    #region 流程简介
                    //1.同级目录添加 Authorization 文件夹
                    //2.往新增的 Authorization 文件夹中添加 xxxPermissions.cs 文件
                    //3.往新增的 Authorization 文件夹中添加 xxxAuthorizationProvider.cs 文件
                    //4.往当前项目根目录下文件夹 Authorization 里面的AppAuthorizationProvider.cs类中的SetPermissions方法最后加入 SetxxxPermissions(pages);
                    //5.往xxxxx.Application项目中增加当前所选文件所在的文件夹
                    //6.往第五步新增的文件夹中增加Dto目录
                    //7.往第六步新增的Dto中增加CreateOrUpdatexxxInput.cs  xxxEditDto.cs  xxxListDto.cs  GetxxxForEditOutput.cs  GetxxxsInput.cs这五个文件
                    //8.编辑CustomDtoMapper.cs,添加映射
                    //9.往第五步新增的文件夹中增加 xxxAppService.cs和IxxxAppService.cs 类
                    //10.编辑DbContext
                    //11.新增前端文件
                    #endregion

                    #region 流程实现
                    ////1.同级目录添加 Authorization 文件夹
                    //var authorizationFolder = selectProjectItem.ProjectItems.AddFolder("Authorization");//向同级目录插入文件夹

                    ////2.往新增的 Authorization 文件夹中添加 xxxPermissions.cs 文件
                    //CreatePermissionFile(applicationStr, className, authorizationFolder);

                    ////3.往新增的 Authorization 文件夹中添加 xxxAuthorizationProvider.cs 文件
                    //CreateAppAuthorizationProviderFile(applicationStr, className, classCnName, authorizationFolder);

                    ////4.往当前项目根目录下文件夹 Authorization 里面的 AppAuthorizationProvider.cs类中的 SetPermissions 方法最后加入 SetxxxPermissions(pages);
                    //SetPermission(topProject, className);

                    ////5.往xxxxx.Application项目中增加当前所选文件所在的文件夹
                    //ProjectItem applicationProjectItem = solutionProjectItems.Find(t => t.Name == applicationStr + ".Application");
                    //var applicationNewFolder = applicationProjectItem.SubProject.ProjectItems.Item(dirPath);
                    //if (applicationNewFolder == null)
                    //{
                    //    applicationNewFolder = applicationProjectItem.SubProject.ProjectItems.AddFolder(dirPath);
                    //}

                    ////6.往第五步新增的文件夹中增加Dto目录
                    //var applicationDtoFolder = applicationNewFolder.ProjectItems.Item("Dto");
                    //if (applicationDtoFolder == null)
                    //{
                    //    applicationDtoFolder = applicationNewFolder.ProjectItems.AddFolder("Dto");
                    //}

                    ////7.往第六步新增的Dto中增加CreateOrUpdatexxxInput.cs  xxxEditDto.cs  xxxListDto.cs  GetxxxForEditOutput.cs  GetxxxsInput.cs这五个文件
                    DtoFileModel dtoModel = GetDtoModel(applicationStr, className, classCnName, classDescription, dirPath, codeClass);
                    //CreateDtoFile(dtoModel, className, applicationDtoFolder);

                    ////8.编辑CustomDtoMapper.cs,添加映射
                    //SetMapper(applicationProjectItem.SubProject, className, classCnName);

                    ////9.往第五步新增的文件夹中增加 xxxAppService.cs和IxxxAppService.cs 类
                    //CreateServiceFile(applicationStr, className, classCnName, applicationNewFolder, dirPath, codeClass);

                    ////10.编辑DbContext
                    //ProjectItem entityFrameworkProjectItem = solutionProjectItems.Find(t => t.Name == applicationStr + ".EntityFrameworkCore");
                    //SetDbSetToDbContext(entityFrameworkProjectItem.SubProject, namespaceStr, className);

                    //11.生成前端
                    frontBaseUrl = topProject.FullName.Substring(0, topProject.FullName.IndexOf("src") - 1);
                    frontBaseUrl = frontBaseUrl.Substring(0, frontBaseUrl.LastIndexOf("\\")) + "\\angular\\src\\";

                    //11.1 往app\\admin文件夹下面加xxx文件夹
                    string componetBasePath = frontBaseUrl + "app\\admin\\" + dirPath.ToLower();
                    if (!Directory.Exists(componetBasePath))
                    {
                        Directory.CreateDirectory(componetBasePath);
                    }

                    //11.2 往新增的文件夹加xxx.component.html   xxx.component.ts   create-or-edit-xxx-modal.component.html  create-or-edit-xxx-modal.component.ts这4个文件
                    CreateFrontFile(dtoModel, className, componetBasePath);
                    //11.3 修改app\\admin\\admin.module.ts文件,  import新增的组件   注入组件
                    EditModule(frontBaseUrl, className, dirPath);
                    //11.4 修改app\\admin\\admin-routing.module.ts文件   添加路由
                    EditRouter(frontBaseUrl, className, dirPath);
                    //11.5 修改 app\\shared\\layout\\nav\\app-navigation.service.ts文件   添加菜单
                    AddMenu(frontBaseUrl, classCnName, className);
                    //11.6 修改 shared\\service-proxies\\service-proxy.module.ts文件  提供服务
                    AddProxy(frontBaseUrl, className);

                    //如果需要新增一级目录的话,需要修改app\\\app-routing.module.ts文件

                    message = "生成成功!";
                    #endregion
                }
            }
            string title = "abp代码生成器";

            // Show a message box to prove we were here
            VsShellUtilities.ShowMessageBox(
                asyncPackage,
                message,
                title,
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
        }
예제 #24
0
 private void ProjectItemsEvents_ItemRenamed(EnvDTE.ProjectItem ProjectItem, string OldName)
 {
     _clippy.StartAnimation(ClippyAnimation.Writing, true);
 }
예제 #25
0
        public void TestAutomationOnProjectItem()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the global service provider and the dte
                IServiceProvider sp = VsIdeTestHostContext.ServiceProvider;
                DTE dte             = (DTE)sp.GetService(typeof(DTE));

                string destination = Path.Combine(TestContext.TestDir, TestContext.TestName);
                Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true);

                OAProject automation = Utilities.FindExtObject(sp, Utilities.NestedProjectGuid, TestContext.TestName) as OAProject;
                Assert.IsNotNull(automation, "Failed to create a project using automation");

                ProjectNode project = automation.Project;

                // Get the AssemblyInfo.cs, try to open it and then ask using automation that it is opened.
                EnvDTE.ProjectItem item = automation.ProjectItems.Item("AssemblyInfo.cs");
                Assert.IsNotNull(item, "Could not retrieve AssemblyInfo.cs");

                EnvDTE.Window window = item.Open(VSConstants.LOGVIEWID_Primary.ToString());
                Assert.IsNotNull(window, "Could not open the AssemblyInfo.cs");
                window.Activate();

                bool isOpen = item.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString());
                Assert.IsTrue(isOpen, "The AssemblyInfo.cs file should have been opened");

                // Now save it
                item.Save("");

                Assert.IsTrue(item.Saved, "The renamed AssemblyInfo.cs has not been saved");

                // Get the Document
                EnvDTE.Document document = item.Document;
                Assert.IsNotNull(document, "Could not retrieve the document object");
                Assert.IsTrue(document.Name == "AssemblyInfo.cs", "The document for the file item is incorrect. It's name should be AssemblyInfo.cs");

                // Try the properties on a nested item
                EnvDTE.ProjectItem nestedProject     = automation.ProjectItems.Item("ANestedProject");
                EnvDTE.ProjectItem nestedProjectItem = nestedProject.ProjectItems.Item("Program.cs");
                EnvDTE.Properties nesteditemsProps   = nestedProjectItem.Properties;
                EnvDTE.Property nestedItemProperty   = nesteditemsProps.Item("BuildAction");
                Assert.IsNotNull(nestedItemProperty, "Could not retrieve the BuildAction property from the nested project item");
                nestedItemProperty.Value = BuildAction.Content;
                Assert.AreEqual((BuildAction)nestedItemProperty.Value, BuildAction.Content);

                // Now try the properties on the top project item
                EnvDTE.Properties props = item.Properties;
                Assert.IsNotNull(props, "Could not retrieve the BuildAction property from the nested project item");

                EnvDTE.Property itemProperty = props.Item("BuildAction");
                Assert.IsNotNull(itemProperty, "Could not retrieve the BuildAction property from the nested project item");
                Assert.IsFalse(itemProperty is OANullProperty, "Could not retrieve the BuildAction property from the nested project item");
                itemProperty.Value = BuildAction.Content;
                Assert.AreEqual(itemProperty.Value, BuildAction.Content);

                // Now save as
                Assert.IsTrue(item.SaveAs("AssemblyInfo1.cs"), "The file AssemblyInfo.cs could not be reanmed to AssemblyInfo1.cs");
                Assert.IsTrue(item.Name == "AssemblyInfo1.cs", "File item has been renamed to AssemblyInfo1.cs but the Name property has not");

                // Now try the Program.cs. That should not be opened
                EnvDTE.ProjectItem item1 = automation.ProjectItems.Item("Program.cs");

                Assert.IsNotNull(item1, "Could not retrieve AssemblyInfo.cs");

                isOpen = item1.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString());

                Assert.IsFalse(isOpen, "The Program.cs should not have been opened");

                // Now get the Reference folder as a project item and expand it.
                EnvDTE.ProjectItem references = automation.ProjectItems.Item("References");
                references.ExpandView();

                // Check that actually it was expanded.
                IVsUIHierarchyWindow uiHierarchy     = VsShellUtilities.GetUIHierarchyWindow(project.Site, HierarchyNode.SolutionExplorer);
                System.Reflection.MethodInfo mi      = typeof(ProjectNode).GetMethod("FindChild", BindingFlags.NonPublic | BindingFlags.Instance);
                ReferenceContainerNode containerNode = (ReferenceContainerNode)mi.Invoke(project, new object[] { "References" });

                __VSHIERARCHYITEMSTATE state;
                uint stateAsInt;
                uiHierarchy.GetItemState(project, (uint)containerNode.ID, (uint)__VSHIERARCHYITEMSTATE.HIS_Expanded, out stateAsInt);
                state = (__VSHIERARCHYITEMSTATE)stateAsInt;
                Assert.IsTrue(state == __VSHIERARCHYITEMSTATE.HIS_Expanded, "The References folder has not been expanded");
            });
        }
예제 #26
0
 private void ProjectItemsEvents_ItemRemoved(EnvDTE.ProjectItem ProjectItem)
 {
     _clippy.StartAnimation(ClippyAnimation.EmptyTrash, true);
 }
예제 #27
0
        private void TestImplicitNestedProjectReload(IServiceProvider sp, ProjectNode project, int dialogAnswer)
        {
            // Save everything.
            IVsSolution solutionService = (IVsSolution)sp.GetService(typeof(IVsSolution));

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

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

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

            string nestedProjectFileName = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

            if (dialogAnswer == NativeMethods.IDYES)
            {
                Assert.IsTrue(found, "The nested project file has not been reloaded correctly");
            }
            else
            {
                Assert.IsFalse(found, "The nested project file has been reloaded but was asked not to do that.");
            }
        }
예제 #28
0
 private void ProjectItemsEvents_ItemAdded(EnvDTE.ProjectItem ProjectItem)
 {
     _clippy.StartAnimation(ClippyAnimation.Congratulate, true);
 }
예제 #29
0
        private File AddFileToFolder(Folder folder, ProjectItem item)
        {
            var newFile = new FileProxy(folder);
            newFile.VsProjectItem = item;
            newFile.Name = item.Name;
            folder.Items.Add(newFile);

            foreach (ProjectItem codeBehindItem in item.ProjectItems)
            {
                var codeBehindFile = new FileProxy(folder);
                codeBehindFile.Name = codeBehindItem.Name;
                codeBehindFile.VsProjectItem = codeBehindItem;
                newFile.Items.Add(codeBehindFile);
            }

            return newFile;
        }
예제 #30
0
        public ORMGeneratorSelectionControl(EnvDTE.ProjectItem projectItem, IServiceProvider serviceProvider)
            : this()
        {
            _projectItem     = projectItem;
            _serviceProvider = serviceProvider;
#if VISUALSTUDIO_10_0
            ProjectRootElement project         = ProjectRootElement.TryOpen(projectItem.ContainingProject.FullName);
            string             projectFullPath = project.FullPath;
#else // VISUALSTUDIO_10_0
            Microsoft.Build.BuildEngine.Project project = Engine.GlobalEngine.GetLoadedProject(projectItem.ContainingProject.FullName);
            string projectFullPath = project.FullFileName;
#endif // VISUALSTUDIO_10_0
            _project = project;

            string projectItemRelativePath = (string)projectItem.Properties.Item("LocalPath").Value;
            projectItemRelativePath  = (new Uri(projectFullPath)).MakeRelativeUri(new Uri(projectItemRelativePath)).ToString();
            _projectItemRelativePath = projectItemRelativePath;

#if VISUALSTUDIO_10_0
            ProjectItemGroupElement originalItemGroup = ORMCustomTool.GetItemGroup(project, projectItemRelativePath);
#else // VISUALSTUDIO_10_0
            BuildItemGroup originalItemGroup = ORMCustomTool.GetItemGroup(project, projectItemRelativePath);
#endif // VISUALSTUDIO_10_0
            _originalItemGroup = originalItemGroup;

            string sourceFileName = projectItem.Name;
            _sourceFileName = sourceFileName;
            this.textBox_ORMFileName.Text = sourceFileName;

            this.button_SaveChanges.Click += new EventHandler(this.SaveChanges);
            this.button_Cancel.Click      += new EventHandler(this.Cancel);

            ITree tree = (ITree)(this.virtualTreeControl.MultiColumnTree = new MultiColumnTree(2));
            this.virtualTreeControl.SetColumnHeaders(new VirtualTreeColumnHeader[]
            {
                // TODO: Localize these.
                new VirtualTreeColumnHeader("Generated File Format", 0.30f, VirtualTreeColumnHeaderStyles.ColumnPositionLocked | VirtualTreeColumnHeaderStyles.DragDisabled),
                new VirtualTreeColumnHeader("Generated File Name", 1f, VirtualTreeColumnHeaderStyles.ColumnPositionLocked | VirtualTreeColumnHeaderStyles.DragDisabled)
            }, true);
            MainBranch mainBranch = this._mainBranch = new MainBranch(this
#if VISUALSTUDIO_15_0
                                                                      , serviceProvider
#endif
                                                                      );
            int   totalCount     = mainBranch.VisibleItemCount;
            int[] primaryIndices = new int[totalCount];
            for (int i = 0; i < totalCount; ++i)
            {
                if (mainBranch.IsPrimaryDisplayItem(i))
                {
                    primaryIndices[i] = i - totalCount;
                }
                else
                {
                    primaryIndices[i] = i + 1;
                }
            }
            Array.Sort <int>(primaryIndices);
            int lastPrimary = -1;
            for (int i = 0; i < totalCount; ++i)
            {
                int modifiedIndex = primaryIndices[i];
                if (modifiedIndex < 0)
                {
                    primaryIndices[i] = modifiedIndex + totalCount;
                }
                else
                {
                    if (lastPrimary == -1)
                    {
                        lastPrimary = i - 1;
                    }
                    primaryIndices[i] = modifiedIndex - 1;
                }
            }
            int modifierCount = totalCount - mainBranch.Branches.Count;
            tree.Root = (lastPrimary == -1) ? (IBranch)mainBranch : new BranchPartition(
                mainBranch,
                primaryIndices,
                new BranchPartitionSection(0, lastPrimary + 1),
                new BranchPartitionSection(totalCount - modifierCount, modifierCount, "Generated File Modifiers", false),
                new BranchPartitionSection(lastPrimary + 1, totalCount - lastPrimary - modifierCount - 1, "Intermediate and Secondary Files", true));                 // UNDONE: Localize Header
            this.virtualTreeControl.ShowToolTips   = true;
            this.virtualTreeControl.FullCellSelect = true;

            Dictionary <string, PseudoBuildItem> pseudoItemsByOutputFormat = new Dictionary <string, PseudoBuildItem>(StringComparer.OrdinalIgnoreCase);
            _pseudoItemsByOutputFormat = pseudoItemsByOutputFormat;
            IDictionary <string, IORMGenerator> generators =
#if VISUALSTUDIO_15_0
                ORMCustomTool.GetORMGenerators(serviceProvider);
#else
                ORMCustomTool.ORMGenerators;
#endif
            if (originalItemGroup != null)
            {
#if VISUALSTUDIO_10_0
                foreach (ProjectItemElement buildItem in originalItemGroup.Items)
#else // VISUALSTUDIO_10_0
                foreach (BuildItem buildItem in originalItemGroup)
#endif // VISUALSTUDIO_10_0
                {
                    // Do this very defensively so that the dialog can still be opened if a project is out
                    // of step with the generators registered on a specific machine.
                    string        generatorNameData;
                    string[]      generatorNames;                // The first string is the primary generator, others are the format modifiers
                    int           generatorNameCount;
                    IORMGenerator primaryGenerator;
                    MainBranch.OutputFormatBranch primaryFormatBranch;
                    if (!string.IsNullOrEmpty(generatorNameData = buildItem.GetEvaluatedMetadata(ITEMMETADATA_ORMGENERATOR)) &&
                        !string.IsNullOrEmpty(generatorNameData = generatorNameData.Trim()) &&
                        string.Equals(buildItem.GetEvaluatedMetadata(ITEMMETADATA_DEPENDENTUPON), sourceFileName, StringComparison.OrdinalIgnoreCase) &&
                        null != (generatorNames = generatorNameData.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)) &&
                        0 != (generatorNameCount = generatorNames.Length) &&
                        // This assumes that each generator target of the same type has all of the same options.
                        // This is currently the result of this dialog, and we're not considering hand edits
                        // to the project file at this point.
                        generators.TryGetValue(generatorNames[0], out primaryGenerator) &&
                        mainBranch.Branches.TryGetValue(primaryGenerator.ProvidesOutputFormat, out primaryFormatBranch))
                    {
                        PseudoBuildItem pseudoItem;
                        string          outputFormat = primaryGenerator.ProvidesOutputFormat;

                        if (!pseudoItemsByOutputFormat.TryGetValue(outputFormat, out pseudoItem))
                        {
                            // Note that we can't use the build item file name here as it might be decorated with
                            // target names. Go back to the generator to get an undecorated default name.
                            pseudoItem = new PseudoBuildItem(generatorNameData, primaryGenerator.GetOutputFileDefaultName(sourceFileName));
                            pseudoItemsByOutputFormat.Add(outputFormat, pseudoItem);

                            if (primaryFormatBranch.SelectedORMGenerator == null)
                            {
                                primaryFormatBranch.SelectedORMGenerator = primaryGenerator;
                            }

                            // Format modifiers are attached to the end of the list
                            for (int i = 1; i < generatorNameCount; ++i)
                            {
                                MainBranch.OutputFormatBranch modifierBranch = primaryFormatBranch.NextModifier;
                                string findName = generatorNames[i];
                                while (modifierBranch != null)
                                {
                                    IORMGenerator testGenerator = modifierBranch.ORMGenerators[0];
                                    if (testGenerator.OfficialName == findName)
                                    {
                                        modifierBranch.SelectedORMGenerator = testGenerator;
                                        break;
                                    }
                                    modifierBranch = modifierBranch.NextModifier;
                                }
                            }
                        }

                        pseudoItem.AddOriginalInstance(generatorNameData, ORMCustomToolUtility.GeneratorTargetsFromBuildItem(buildItem));
                    }
                }
            }
        }
예제 #31
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 MenuItemCallback(object sender, EventArgs e)
        {
            var myCommand = sender as OleMenuCommand;

            EnvDTE80.DTE2 applicationObject = this.ServiceProvider.GetService(typeof(DTE)) as EnvDTE80.DTE2;
            object[]      selectedItems     = (object[])applicationObject.ToolWindows.SolutionExplorer.SelectedItems;
            var           processArray      = new List <ShaderCompileData>();

            FindHLSLCompiler(out string fxc, "fxc.exe");
            FindHLSLCompiler(out string dxc, "dxc.exe");

            foreach (EnvDTE.UIHierarchyItem selectedUIHierarchyItem in selectedItems)
            {
                if (selectedUIHierarchyItem.Object is EnvDTE.ProjectItem)
                {
                    EnvDTE.ProjectItem item = selectedUIHierarchyItem.Object as EnvDTE.ProjectItem;
                    int    size             = item.FileCount;
                    string fileName         = item.FileNames[0];
                    if (IsShaderFile(fileName, out ShaderType shaderType))
                    {
                        StreamReader reader = new StreamReader(fileName);
                        if (reader != null)
                        {
                            string content = reader.ReadToEnd();
                            DetermineShaderLanguage(content, out ShaderLanguage language);
                            ProcessStartInfo info = null;
                            FindShaderMacros(content, language, out string[] macros);
                            String outFile         = Path.GetFileName(fileName) + ".bin";
                            String inFileFolder    = Path.GetDirectoryName(fileName);
                            String outFileFullPath = String.Format("{0}\\{1}", inFileFolder, outFile);

                            switch (language)
                            {
                            case ShaderLanguage.HLSL:
                            {
                                DetermineShaderTarget(shaderType, fxc, dxc, out string shaderTarget, out string compiler);
                                if (compiler == "")
                                {
                                    WriteToOutputWindow("Cannot find HLSL Compiler. Make sure your Windows SDK has fxc.exe (dxc.exe for raytracing shader)");
                                    continue;
                                }
                                GenerateHLSLArguments(shaderType, fileName, outFile, shaderTarget, out string compilerArguments);
                                info = new ProcessStartInfo
                                {
                                    UseShellExecute        = false,
                                    FileName               = String.Format("\"{0}\"", compiler),
                                    Arguments              = compilerArguments,
                                    RedirectStandardError  = true,
                                    RedirectStandardOutput = true,
                                    CreateNoWindow         = true,
                                };
                                break;
                            }

                            case ShaderLanguage.VULKAN_GLSL:
                            {
                                String configFileName   = "config.conf";
                                String vulkanSDK        = Environment.GetEnvironmentVariable("VULKAN_SDK");
                                String glslangValidator = vulkanSDK + "\\Bin\\glslangValidator.exe";
                                bool   useConfigFile    = File.Exists(fileName + "\\..\\" + configFileName);
                                configFileName = String.Format("\"{0}\"", Path.Combine(fileName + "\\..\\", configFileName));
                                info           = new ProcessStartInfo
                                {
                                    UseShellExecute        = false,
                                    FileName               = glslangValidator,
                                    Arguments              = String.Format("{0} -V \"{1}\" -o \"{2}\"", useConfigFile ? configFileName : " ", fileName, outFileFullPath),
                                    RedirectStandardError  = true,
                                    RedirectStandardOutput = true,
                                    CreateNoWindow         = true,
                                };
                                break;
                            }
                            }

                            for (int i = 0; i < macros.Length; ++i)
                            {
                                String prevArgs    = info.Arguments;
                                String macroFormat = String.Format("_{0}_{1}", processArray.Count, outFile);

                                info.Arguments += macros[i];
                                info.Arguments  = info.Arguments.Replace(outFile, macroFormat);
                                WriteToOutputWindow(String.Format("Compiling {0}:\n\t {1} {2}\n", fileName, info.FileName, info.Arguments));
                                processArray.Add(new ShaderCompileData
                                {
                                    fileName    = fileName,
                                    outFileName = outFileFullPath.Replace(outFile, macroFormat),
                                    language    = language,
                                    macros      = macros[i].TrimStart().TrimEnd().Replace("-D", "").Replace("\"", ""),
                                    process     = System.Diagnostics.Process.Start(info),
                                });
                                info.Arguments = prevArgs;
                            }
                        }
                    }
                    else
                    {
                        WriteToOutputWindow(String.Format("Not supported : {0} Supported extensions are {1}\n",
                                                          Path.GetFileName(fileName), String.Join(", ", shaderExtensions)));
                    }
                }
            }

            for (int i = 0; i < processArray.Count; ++i)
            {
                // glslangValidator error message format

                /*
                 * ERROR: C:\Users\agent47\Documents\Experimental\VisualStudio\ConsoleApp1\ConsoleApp1\skybox.frag:24: '' :  syntax error, unexpected IDENTIFIER
                 */
                String errorLog = processArray[i].language == ShaderLanguage.VULKAN_GLSL ?
                                  processArray[i].process.StandardOutput.ReadToEnd() : processArray[i].process.StandardError.ReadToEnd();
                processArray[i].process.WaitForExit();
                if (processArray[i].process.ExitCode != 0)
                {
                    // For Vulkan format the error message so user can double click on it in output window to get to exact line with error
                    if (processArray[i].language == ShaderLanguage.VULKAN_GLSL)
                    {
                        errorLog = errorLog.Replace("ERROR: ", "");
                        String pattern        = "([A-Za-z.0-9]+):(\\d+):";
                        Regex  regex          = new Regex(pattern);
                        String replacement    = String.Format("$1($2):");
                        String formattedError = regex.Replace(errorLog, replacement);
                        errorLog = formattedError;
                    }
                    WriteToOutputWindow(String.Format("Failure : Shader {0} {1}\n{2}", Path.GetFileName(processArray[i].fileName), processArray[i].macros, errorLog));
                }
                else
                {
                    WriteToOutputWindow(String.Format("Success : Shader {0} {1} compiled successfully\n", Path.GetFileName(processArray[i].fileName), processArray[i].macros));
                }

                // Cleanup
                if (processArray[i].language == ShaderLanguage.VULKAN_GLSL)
                {
                    File.Delete(String.Format("SPIRV_OUTPUT_{0}.bin", i));
                }
                File.Delete(processArray[i].outFileName);
            }
        }
예제 #32
0
        protected override void OnClosed(EventArgs e)
        {
            if (_savedChanges)
            {
                // Make sure the current document has the necessary
                // extensions loaded.
                // UNDONE: We should be able to do this with the document
                // closed or open as text as well via a registered service
                // on the ORMDesignerPackage, but this is sufficient for now.
                Dictionary <string, string> requiredExtensions = null;
                string[] loadedExtensions = null;
                foreach (IORMGenerator selectedGenerator in _mainBranch.SelectedGenerators)
                {
                    foreach (string requiredExtension in selectedGenerator.GetRequiredExtensionsForInputFormat("ORM"))
                    {
                        if (loadedExtensions == null)
                        {
                            loadedExtensions = (new ORMExtensionManager(_projectItem)).GetLoadedExtensions(_serviceProvider);
                        }
                        if (Array.BinarySearch <string>(loadedExtensions, requiredExtension) < 0)
                        {
                            if (requiredExtensions == null)
                            {
                                requiredExtensions = new Dictionary <string, string>();
                            }
                            else if (requiredExtensions.ContainsKey(requiredExtension))
                            {
                                continue;
                            }
                            requiredExtensions.Add(requiredExtension, requiredExtension);
                        }
                    }
                }
                if (requiredExtensions != null)
                {
                    _savedChanges = ORMExtensionManager.EnsureExtensions(_projectItem, _serviceProvider, requiredExtensions.Values);
                }
            }
            if (_savedChanges)
            {
#if VISUALSTUDIO_10_0
                ProjectItemGroupElement itemGroup = _originalItemGroup;
                ProjectRootElement      project   = _project;
#else // VISUALSTUDIO_10_0
                BuildItemGroup itemGroup = _originalItemGroup;
                Microsoft.Build.BuildEngine.Project project = _project;
#endif // VISUALSTUDIO_10_0
                EnvDTE.ProjectItem projectItem    = _projectItem;
                string             sourceFileName = _sourceFileName;
                Dictionary <string, PseudoBuildItem> pseudoItems = _pseudoItemsByOutputFormat;
                IDictionary <string, IORMGenerator>  generators  =
#if VISUALSTUDIO_15_0
                    ORMCustomTool.GetORMGenerators(_serviceProvider);
#else
                    ORMCustomTool.ORMGenerators;
#endif
                PseudoBuildItem pseudoItem;
                string          generatorNameData;        // The first string is the primary generator, others are the format modifiers, space delimited
                IVsShell        shell;

                Dictionary <string, IORMGenerator> generatorsWithTargetsByOutputFormat = null;
                IDictionary <string, ORMCustomToolUtility.GeneratorTargetSet> targetSetsByFormatName = null;
                foreach (PseudoBuildItem testPseudoItem in pseudoItems.Values)
                {
                    string         primaryGeneratorName;
                    IList <string> generatorTargets;
                    IORMGenerator  generator;
                    if (!string.IsNullOrEmpty(generatorNameData = testPseudoItem.CurrentGeneratorNames) &&
                        null != (primaryGeneratorName = ORMCustomToolUtility.GetPrimaryGeneratorName(generatorNameData)) &&
                        generators.TryGetValue(primaryGeneratorName, out generator) &&
                        null != (generatorTargets = generator.GeneratorTargetTypes) &&
                        0 != generatorTargets.Count)
                    {
                        (generatorsWithTargetsByOutputFormat ?? (generatorsWithTargetsByOutputFormat = new Dictionary <string, IORMGenerator>(StringComparer.OrdinalIgnoreCase)))[generator.ProvidesOutputFormat] = generator;
                    }
                }
                if (generatorsWithTargetsByOutputFormat != null)
                {
                    IDictionary <string, GeneratorTarget[]> docTargets = null;
                    EnvDTE.Document projectItemDocument = projectItem.Document;
                    string          itemPath;
                    if (projectItemDocument != null)
                    {
                        using (Stream targetsStream = ORMCustomToolUtility.GetDocumentExtension <Stream>(projectItemDocument, "ORMGeneratorTargets", itemPath = projectItem.get_FileNames(0), _serviceProvider))
                        {
                            if (targetsStream != null)
                            {
                                targetsStream.Seek(0, SeekOrigin.Begin);
                                docTargets = new BinaryFormatter().Deserialize(targetsStream) as IDictionary <string, GeneratorTarget[]>;
                            }
                        }
                    }
                    else if (null != (shell = _serviceProvider.GetService(typeof(SVsShell)) as IVsShell))
                    {
                        Guid       pkgId = typeof(ORMDesignerPackage).GUID;
                        IVsPackage package;
                        if (0 != shell.IsPackageLoaded(ref pkgId, out package) || package == null)
                        {
                            shell.LoadPackage(ref pkgId, out package);
                        }

                        // Temporarily load the document so that the generator targets can be resolved.
                        using (Store store = new ModelLoader(ORMDesignerPackage.ExtensionLoader, true).Load(projectItem.get_FileNames(0)))
                        {
                            docTargets = GeneratorTarget.ConsolidateGeneratorTargets(store as IFrameworkServices);
                        }
                    }

                    // We have generators that care about targets, which means that ExpandGeneratorTargets will
                    // product placeholder targets for these generators even if docTargets is currently null.
                    // This allows the dialog to turn on a generator before the data (or even extension) to feed
                    // it is available in the model and provides a smooth transition in and out of this placeholder
                    // state. It is up to the individual generators to proceed without explicit target data or
                    // to produce a message for the user with instructions on how to add the data to the model.
                    Dictionary <string, string> generatorNamesByOutputFormat = new Dictionary <string, string>();
                    foreach (KeyValuePair <string, PseudoBuildItem> pair in pseudoItems)
                    {
                        generatorNameData = pair.Value.CurrentGeneratorNames;
                        if (!string.IsNullOrEmpty(generatorNameData))
                        {
                            generatorNamesByOutputFormat[pair.Key] = ORMCustomToolUtility.GetPrimaryGeneratorName(generatorNameData);
                        }
                    }
                    targetSetsByFormatName = ORMCustomToolUtility.ExpandGeneratorTargets(generatorNamesByOutputFormat, docTargets
#if VISUALSTUDIO_15_0
                                                                                         , _serviceProvider
#endif // VISUALSTUDIO_15_0
                                                                                         );
                }

                Dictionary <string, BitTracker> processedGeneratorTargets = null;
                if (targetSetsByFormatName != null)
                {
                    processedGeneratorTargets = new Dictionary <string, BitTracker>();
                    foreach (KeyValuePair <string, ORMCustomToolUtility.GeneratorTargetSet> kvp in targetSetsByFormatName)
                    {
                        processedGeneratorTargets[kvp.Key] = new BitTracker(kvp.Value.Instances.Length);
                    }
                }

                if (null != itemGroup)
                {
#if VISUALSTUDIO_10_0
                    Dictionary <string, ProjectItemElement> removedItems = null;
                    foreach (ProjectItemElement item in itemGroup.Items)
#else // VISUALSTUDIO_10_0
                    Dictionary <string, BuildItem> removedItems = null;
                    foreach (BuildItem item in itemGroup)
#endif // VISUALSTUDIO_10_0
                    {
                        string        primaryGeneratorName;
                        string        outputFormat;
                        IORMGenerator generator;
                        if (null != (primaryGeneratorName = ORMCustomToolUtility.GetPrimaryGeneratorName(item.GetEvaluatedMetadata(ITEMMETADATA_ORMGENERATOR))) &&
                            string.Equals(item.GetEvaluatedMetadata(ITEMMETADATA_DEPENDENTUPON), sourceFileName, StringComparison.OrdinalIgnoreCase) &&
                            generators.TryGetValue(primaryGeneratorName, out generator) &&
                            pseudoItems.TryGetValue(outputFormat = generator.ProvidesOutputFormat, out pseudoItem))
                        {
                            generatorNameData = pseudoItem.CurrentGeneratorNames;
                            ORMCustomToolUtility.GeneratorTargetSet targetSet = null;
                            BitTracker processedForFormat = default(BitTracker);
                            if (targetSetsByFormatName != null)
                            {
                                if (targetSetsByFormatName.TryGetValue(outputFormat, out targetSet))
                                {
                                    processedForFormat = processedGeneratorTargets[outputFormat];
                                }
                            }

                            List <PseudoBuildInstance> originalInstances;
                            bool removeInstance = false;
                            if (string.IsNullOrEmpty(generatorNameData))
                            {
                                // The item is deleted, mark for removal
                                removeInstance = true;
                            }
                            else if (null != (originalInstances = pseudoItem.OriginalInstances))
                            {
                                for (int i = 0, count = originalInstances.Count; i < count && !removeInstance; ++i)
                                {
                                    PseudoBuildInstance instance = originalInstances[i];
                                    if (instance.IsRemoved)
                                    {
                                        continue;
                                    }

                                    GeneratorTarget[] targets = instance.OriginalGeneratorTargets;
                                    if (targetSet != null)
                                    {
                                        if (targets == null)
                                        {
                                            // Remove, if a target set is available then it must be used
                                            removeInstance = true;
                                        }
                                        else
                                        {
                                            int instanceIndex = targetSet.IndexOfInstance(targets, delegate(int ignoreInstance) { return(processedForFormat[ignoreInstance]); });
                                            if (instanceIndex == -1)
                                            {
                                                removeInstance = true;
                                            }
                                            else if (!processedForFormat[instanceIndex])
                                            {
                                                if (instance.OriginalGeneratorNames != generatorNameData)
                                                {
                                                    // This is a preexisting item, update its meta information
                                                    ORMCustomToolUtility.SetItemMetaData(item, ITEMMETADATA_ORMGENERATOR, generatorNameData);
                                                }
                                                processedForFormat[instanceIndex]       = true;
                                                processedGeneratorTargets[outputFormat] = processedForFormat;
                                                break;
                                            }
                                        }
                                    }
                                    else if (targets != null)
                                    {
                                        // Remove, formatter changed to one that does not use a generator target
                                        removeInstance = true;
                                    }
                                    else if (instance.OriginalGeneratorNames != generatorNameData)
                                    {
                                        // This is a preexisting item, update its meta information
                                        ORMCustomToolUtility.SetItemMetaData(item, ITEMMETADATA_ORMGENERATOR, generatorNameData);
                                    }

                                    if (removeInstance)
                                    {
                                        instance.IsRemoved = true;
                                    }
                                }
                            }

                            if (removeInstance)
                            {
                                if (removedItems == null)
                                {
#if VISUALSTUDIO_10_0
                                    removedItems = new Dictionary <string, ProjectItemElement>();
#else // VISUALSTUDIO_10_0
                                    removedItems = new Dictionary <string, BuildItem>();
#endif // VISUALSTUDIO_10_0
                                }
                                removedItems[ORMCustomToolUtility.GetItemInclude(item)] = item;
                            }
                        }
                    }
                    if (removedItems != null)
                    {
                        EnvDTE.ProjectItems subItems = projectItem.ProjectItems;
#if VISUALSTUDIO_10_0
                        foreach (KeyValuePair <string, ProjectItemElement> removePair in removedItems)
                        {
                            ProjectItemElement      removeItem = removePair.Value;
                            ProjectElementContainer removeFrom;
                            if (null != (removeFrom = removeItem.Parent))
                            {
                                removeFrom.RemoveChild(removeItem);
                            }
#else // VISUALSTUDIO_10_0
                        foreach (KeyValuePair <string, BuildItem> removePair in removedItems)
                        {
                            project.RemoveItem(removePair.Value);
#endif // VISUALSTUDIO_10_0
                            try
                            {
                                EnvDTE.ProjectItem subItem = subItems.Item(removePair.Key);
                                if (subItem != null)
                                {
                                    subItem.Delete();
                                }
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                    }

#if !VISUALSTUDIO_10_0
                    // Empty item groups remove themselves from the project, we'll need
                    // to recreate below if the group is empty after the remove phase.
                    if (itemGroup.Count == 0)
                    {
                        itemGroup = null;
                    }
#endif
                }

                // Removes and changes are complete, proceed with adds for any new items
                string newItemDirectory          = null;
                string projectPath               = null;
                EnvDTE.ProjectItems projectItems = null;
                string tmpFile = null;
                // Adding a file to our special item group adds it to the build system. However,
                // it does not add it to the parallel project system, which is what displays in
                // the solution explorer. Therefore, we also explicitly add the item to the
                // project system as well. Unfortunately, this extra add automatically creates
                // a redundant item (usually in a new item group) for our adding item. Track anything
                // we add through the project system so that we can remove these redundant items from the
                // build system when we're done.
                Dictionary <string, string> sideEffectItemNames = null;
                try
                {
                    Action <IORMGenerator, string, ORMCustomToolUtility.GeneratorTargetSet, GeneratorTarget[]> addProjectItem = delegate(IORMGenerator generator, string allGenerators, ORMCustomToolUtility.GeneratorTargetSet targetSet, GeneratorTarget[] targetInstance)
                    {
                        if (itemGroup == null)
                        {
#if VISUALSTUDIO_10_0
                            itemGroup = project.AddItemGroup();
#else
                            itemGroup = project.AddNewItemGroup();
#endif
                            itemGroup.Condition = string.Concat(ITEMGROUP_CONDITIONSTART, _projectItemRelativePath, ITEMGROUP_CONDITIONEND);
                        }
                        if (newItemDirectory == null)
                        {
                            // Initialize general information
#if VISUALSTUDIO_10_0
                            projectPath = project.FullPath;
#else
                            projectPath = project.FullFileName;
#endif
                            newItemDirectory = Path.GetDirectoryName(new Uri(projectPath).MakeRelativeUri(new Uri((string)projectItem.Properties.Item("LocalPath").Value)).ToString());
                            projectItems     = projectItem.ProjectItems;
                        }

                        string defaultFileName  = generator.GetOutputFileDefaultName(sourceFileName);
                        string fileName         = targetInstance == null ? defaultFileName : ORMCustomToolUtility.GeneratorTargetSet.DecorateFileName(defaultFileName, targetInstance);
                        string fileRelativePath = Path.Combine(newItemDirectory, fileName);
                        string fileAbsolutePath = string.Concat(new FileInfo(projectPath).DirectoryName, Path.DirectorySeparatorChar, fileRelativePath);
#if VISUALSTUDIO_10_0
                        ProjectItemElement newBuildItem;
#else
                        BuildItem newBuildItem;
#endif
                        newBuildItem = generator.AddGeneratedFileItem(itemGroup, sourceFileName, fileRelativePath);

                        if (allGenerators != null)
                        {
                            ORMCustomToolUtility.SetItemMetaData(newBuildItem, ITEMMETADATA_ORMGENERATOR, allGenerators);
                        }

                        if (targetInstance != null)
                        {
                            ORMCustomToolUtility.SetGeneratorTargetMetadata(newBuildItem, targetInstance);
                        }

                        (sideEffectItemNames ?? (sideEffectItemNames = new Dictionary <string, string>()))[fileRelativePath] = null;
                        if (File.Exists(fileAbsolutePath))
                        {
                            try
                            {
                                projectItems.AddFromFile(fileAbsolutePath);
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                        else
                        {
                            if (tmpFile == null)
                            {
                                tmpFile = Path.GetTempFileName();
                            }
                            EnvDTE.ProjectItem newProjectItem = projectItems.AddFromTemplate(tmpFile, fileName);
                            string             customTool;
                            if (!string.IsNullOrEmpty(customTool = newBuildItem.GetMetadata(ITEMMETADATA_GENERATOR)))
                            {
                                newProjectItem.Properties.Item("CustomTool").Value = customTool;
                            }
                        }
                    };

                    foreach (KeyValuePair <string, PseudoBuildItem> keyedPseudoItem in pseudoItems)
                    {
                        pseudoItem = keyedPseudoItem.Value;
                        string allGenerators    = pseudoItem.CurrentGeneratorNames;
                        string primaryGenerator = ORMCustomToolUtility.GetPrimaryGeneratorName(allGenerators);
                        if (allGenerators == primaryGenerator)
                        {
                            allGenerators = null;
                        }
                        IORMGenerator generator    = generators[primaryGenerator];
                        string        outputFormat = generator.ProvidesOutputFormat;
                        ORMCustomToolUtility.GeneratorTargetSet targetSet = null;
                        if (targetSetsByFormatName != null)
                        {
                            targetSetsByFormatName.TryGetValue(outputFormat, out targetSet);
                        }

                        if (targetSet != null)
                        {
                            // OriginalInstances were already updated in the remove loop and processed
                            // instances were flagged. Find additional instances from the target set (created
                            // just now from the current model), not from the pseudoItem (created from the project
                            // files that possibly reflect a previous version of the model).
                            GeneratorTarget[][] instances = targetSet.Instances;
                            BitTracker          processed = processedGeneratorTargets[outputFormat];

                            for (int i = 0, count = instances.Length; i < count; ++i)
                            {
                                if (!processed[i])
                                {
                                    addProjectItem(generator, allGenerators, targetSet, instances[i]);
                                }
                            }
                        }
                        else if (pseudoItem.OriginalInstances == null)
                        {
                            addProjectItem(generator, allGenerators, null, null);
                        }
                        else
                        {
                            // Make sure there was an original instance that did not have a target set.
                            List <PseudoBuildInstance> originals = pseudoItem.OriginalInstances;
                            int i = 0, count = originals.Count;
                            for (; i < count; ++i)
                            {
                                if (originals[i].OriginalGeneratorTargets == null)
                                {
                                    break;
                                }
                            }

                            if (i == count)
                            {
                                addProjectItem(generator, allGenerators, null, null);
                            }
                        }
                    }
                }
                finally
                {
                    if (tmpFile != null)
                    {
                        File.Delete(tmpFile);
                    }
                }

                if (sideEffectItemNames != null)
                {
                    ORMCustomToolUtility.RemoveSideEffectItems(sideEffectItemNames, project, itemGroup);
                }

#if VISUALSTUDIO_10_0
                // Old group remove themselves when empty, but this is
                // not true in the new build system. Clean up as needed.
                if (itemGroup != null &&
                    itemGroup.Items.Count == 0)
                {
                    project.RemoveChild(itemGroup);
                }
#endif
                VSLangProj.VSProjectItem vsProjectItem = projectItem.Object as VSLangProj.VSProjectItem;
                if (vsProjectItem != null)
                {
                    vsProjectItem.RunCustomTool();
                }
            }
            base.OnClosed(e);
        }
예제 #33
0
 public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #34
0
 public DeploymentSettings(EnvDTE.ProjectItem projectItm)
 {
     PopulateDeploymentSettings(projectItm.ContainingProject);
 }
예제 #35
0
        /// <summary>
        /// Called when [execute].
        /// </summary>
        public override void Execute()
        {
            string tempfile = Path.GetTempFileName();

            try
            {

                //string foldert = System.IO.Path.GetDirectoryName(Project.FullName);
                string fileFullName = string.Empty;
                //DirectoryInfo dInfo = new DirectoryInfo(foldert);
                ProjectItem folderItem = VSIPHelper.FindItemByName(Project.ProjectItems, Subfolder, true);
                if (folderItem==null)
                    try
                    {
                        project.ProjectItems.AddFolder(Subfolder);
                        folderItem = VSIPHelper.FindItemByName(Project.ProjectItems, Subfolder, true);
                    }
                    catch
                    { }
           
                using (StreamWriter sw = new StreamWriter(tempfile, false, new UTF8Encoding(true, true)))
                {
                    sw.WriteLine(content);
                }

                // Check it the targetFileName already exists and delete it so it can be added.
                ProjectItem targetItem = VSIPHelper.FindItemByName(Project.ProjectItems, targetFileName, true);
                if (targetItem != null)
                {
                    targetItem.Delete();
                }

                if (!String.IsNullOrEmpty(itemName))
                {
                    ProjectItem item = VSIPHelper.FindItemByName(Project.ProjectItems, itemName, true);

                    if (item != null)
                    {
                        projectItem = item.ProjectItems.AddFromTemplate(tempfile, targetFileName);
                    }
                }
                else
                {
                    //projectItem = project.ProjectItems.AddFromTemplate(tempfile, targetFileName);
                    projectItem = folderItem.ProjectItems.AddFromTemplate(tempfile, targetFileName);
                }

                if (open && projectItem != null)
                {
                    Window wnd = projectItem.Open(EnvDTE.Constants.vsViewKindPrimary);
                    wnd.Visible = true;
                    wnd.Activate();
                }
            }
            finally
            {
                File.Delete(tempfile);
            }
        }
예제 #36
0
        public static bool TryGetFolder(this ProjectItems projectItems, string name, out ProjectItem projectItem)
        {
            projectItem = GetProjectItem(projectItems, name, _folderKinds);

            return(projectItem != null);
        }
 private VSTemplateSchema.ProjectItem CreateFileItem(ProjectItem projectItem)
 {
     return new VSTemplateSchema.ProjectItem
                {
                    ReplaceParameters = projectItem.ShouldReplaceParameters(),
                    Value = projectItem.Name,
                    TargetFileName = projectItem.Name,
                    ReplaceParametersSpecified = true
                };
 }
예제 #38
0
 //MiscFilesEvents
 public void MiscFilesEvents_ItemAdded(EnvDTE.ProjectItem projectItem)
 {
     _outputWindowPane.OutputString("MiscFilesEvents, ItemAdded\n");
     _outputWindowPane.OutputString("\tProject Item: " + projectItem.Name + "\n");
 }
        private object CreateLinkedFileItem(ProjectItem projectItem, string parentPath)
        {
            string filename = projectItem.get_FileNames(0);

            string relativepath = PathUtil.RelativePathTo(Path.GetDirectoryName(parentPath), filename);
            return new VSTemplateSchema.ProjectItem
                       {
                           ReplaceParameters = projectItem.ShouldReplaceParameters(),
                           Value = relativepath,
                           TargetFileName = projectItem.Name,
                           ReplaceParametersSpecified = true
                       };
        }
예제 #40
0
 public void SolutionItemsEvents_ItemRemoved(EnvDTE.ProjectItem projectItem)
 {
     _outputWindowPane.OutputString("SolutionItemsEvents, ItemRemoved\n");
     _outputWindowPane.OutputString("\tProject Item: " + projectItem.Name + "\n");
 }
예제 #41
0
        /// <summary>
        /// Determines whether the specified <paramref name="item" /> matches the specified rule.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="rootProjectConfiguration">The root project configuration.</param>
        /// <param name="ruleType">Type of the rule.</param>
        /// <param name="targetProjectType">Type of the target project.</param>
        /// <returns><c>true</c> if the item matches the rule; otherwise <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="item" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="rootProjectConfiguration" /> is <c>null</c>.</exception>
        private bool MatchesRule(ProjectItem item, RootProject rootProjectConfiguration, RuleType ruleType, ProjectType targetProjectType)
        {
            Argument.IsNotNull("item", item);
            Argument.IsNotNull("rootProjectConfiguration", rootProjectConfiguration);

            foreach (var rule in rootProjectConfiguration.Rules)
            {
                if (rule.Type == ruleType)
                {
                    if (string.Compare(rule.Name, item.GetNameRelativeToRoot()) == 0)
                    {
                        foreach (var ruledProjectType in rule.ProjectTypes)
                        {
                            if (ruledProjectType == targetProjectType)
                            {
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }
예제 #42
0
 public void GlobalProjectItemsEvents_ItemRenamed(EnvDTE.ProjectItem projectItem, string OldName)
 {
     _outputWindowPane.OutputString("GlobalProjectItemsEvents, ItemRenamed\n");
     _outputWindowPane.OutputString("\tProject Item: " + projectItem.Name + "\n");
 }
예제 #43
0
        /// <summary>
        /// Determines whether the specified item should be skipped based on the rules in the configuration.
        /// </summary>
        /// <param name="sourceProject">The source project.</param>
        /// <param name="target">The target.</param>
        /// <param name="targetProjectType">Type of the target project.</param>
        /// <returns><c>true</c> if the item should be skipped; otherwise <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="sourceProject" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="target" /> is <c>null</c>.</exception>
        private bool ShouldSkipRemovingOfItem(Project sourceProject, ProjectItem target, ProjectType targetProjectType)
        {
            Argument.IsNotNull("sourceProject", sourceProject);
            Argument.IsNotNull("target", target);

            var rootProjectConfiguration = GetRootProjectConfiguration(sourceProject);

            return MatchesRule(target, rootProjectConfiguration, RuleType.DoNotRemove, targetProjectType);
        }
예제 #44
0
 void IWizard.BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
 {
 }
예제 #45
0
        public static string GetProjectItemPath(ProjectItem projectItem)
        {
            // Get path (1 expected)
            if (projectItem.FileCount != 1)
                return null;

            return projectItem.FileNames[0];
        }
        /// <summary>
        /// The method that creates a new item from the intput string.
        /// </summary>
        public override void Execute()
        {
            DTE vs = (DTE)GetService(typeof(DTE));
            string tempfile = Path.GetTempFileName();
            try
            {
                using (StreamWriter sw = new StreamWriter(tempfile, false, new UTF8Encoding(true, true)))
                {
                    sw.WriteLine(content);
                }

                // Check it the targetFileName already exists and delete it so it can be added.
                ProjectItem targetItem = DteHelperEx.FindItemByName(Project.ProjectItems, targetFileName, true);
                if (targetItem != null)
                {
                    targetItem.Delete();
                }

                if (!String.IsNullOrEmpty(itemName))
                {
                    ProjectItem item = DteHelperEx.FindItemByName(Project.ProjectItems, itemName, true);
                    if (item != null)
                    {
                        projectItem = item.ProjectItems.AddFromTemplate(tempfile, targetFileName);
                    }
                }
                else
                {
                    projectItem = project.ProjectItems.AddFromTemplate(tempfile, targetFileName);
                }

                if (open && projectItem != null)
                {
                    Window wnd = projectItem.Open(Constants.vsViewKindPrimary);
                    wnd.Visible = true;
                    wnd.Activate();
                }
            }
            finally
            {
                File.Delete(tempfile);
            }
        }