private void CreateViewModel(ProjectItems projectItems, CreateMessage model, string classTemplate) { var viewModelProjectItem = projectItems.AddFromTemplate(classTemplate, $"{model.ResponseViewModelName.FullName}"); var codeClass = viewModelProjectItem.FindCodeClassByName(model.ResponseViewModelName.Name); codeClass.Access = vsCMAccess.vsCMAccessPublic; }
private void CreateMessageRequestHandlerInNewFile(ProjectItems projectItems, CreateMessage model, string classTemplate) { var handlerProjectItem = projectItems.AddFromTemplate(classTemplate, $"{model.MessageHandlerName.FullName}"); var handlerCodeClass = handlerProjectItem.FindCodeClassByName(model.MessageHandlerName.Name); handlerCodeClass.Access = vsCMAccess.vsCMAccessPublic; AdjustRequestHandler(handlerCodeClass, model); }
/// <summary> ///创建基于模板的文档 /// </summary> /// <param name="projectItems">某个项目下面的ProjectItems</param> /// <param name="documentType">DocumentType枚举</param> /// <param name="documentName">文档名字(不包含后缀)</param> public void CreateDocumentFromTemplete(ProjectItems projectItems, string documentType, string documentName) { if (VSSolution.CurrentSolution2 != null) { string projectTemplate = VSSolution.CurrentSolution2.GetProjectItemTemplate(documentType, "CSharp"); if (!string.IsNullOrEmpty(projectTemplate)) { projectItems.AddFromTemplate(projectTemplate, documentName); } } }
private static void AddToNewFile(string code, ProjectItems items, string filename) { var tempFile = Path.GetTempFileName(); File.WriteAllText(tempFile, code); var projectItem = items.AddFromTemplate(tempFile, filename); var window = projectItem.Open(); window.Activate(); }
public void AddNewItem(string templateName, string name, string extension, string destinationPath) { var project = GetSelectedProject <IVsHierarchy>()?.GetDTEProject(); if (project != null) { DTE dte = VsAppShell.Current.GetGlobalService <DTE>(); var solution = (Solution2)dte.Solution; // Construct name of the compressed template templateName = Path.ChangeExtension(templateName, "vstemplate"); var templatePath = Path.Combine(GetProjectItemTemplatesFolder(), Path.GetFileNameWithoutExtension(templateName), templateName); // Given path to the project or a folder in it, generate unique file name var fileName = GetUniqueFileName(destinationPath, name, extension); // Locate folder in the project var projectFolder = Path.GetDirectoryName(project.FullName); if (destinationPath.StartsWithIgnoreCase(projectFolder)) { ProjectItems projectItems = project.ProjectItems; if (destinationPath.Length > projectFolder.Length) { var relativePath = destinationPath.Substring(projectFolder.Length + 1); // Go into folders and find project item to insert the file in while (relativePath.Length > 0) { int index = relativePath.IndexOf('\\'); string folder; if (index >= 0) { folder = relativePath.Substring(0, index); relativePath = relativePath.Substring(index + 1); } else { folder = relativePath; relativePath = string.Empty; } try { var item = projectItems.Item(folder); projectItems = item.ProjectItems; } catch (COMException) { return; } } } projectItems?.AddFromTemplate(templatePath, Path.GetFileName(fileName)); } } }
private CodeClass CreateMessageRequest(ProjectItems projectItems, CreateMessage model, string classTemplate) { ThreadHelper.ThrowIfNotOnUIThread(); var requestProjectItem = projectItems.AddFromTemplate(classTemplate, $"{model.MessageName.FullName}"); (requestProjectItem.FileCodeModel as FileCodeModel2).AddNotExistingImports(model.DefaultRequestImports); var codeClass = requestProjectItem.FindCodeClassByName(model.MessageName.Name); codeClass.Access = vsCMAccess.vsCMAccessPublic; codeClass.InsertInterfaceToTheEnd(model.RequestInterface); return(codeClass); }
/// <summary> /// Adds to folder from template. /// </summary> /// <param name="instance">The instance.</param> /// <param name="folderName">Name of the folder.</param> /// <param name="templateName">Name of the template.</param> /// <param name="fileName">Name of the file.</param> /// <param name="createFolder">if set to <c>true</c> [create folder].</param> /// <returns>True or False.</returns> public static bool AddToFolderFromTemplate( this Project instance, string folderName, string templateName, string fileName, bool createFolder) { TraceService.WriteLine("ProjectExtensions::AddToFolderFromTemplate project=" + instance.Name); string path = instance.Properties.Item("FullPath").Value; ProjectItems projectItems = instance.ProjectItems; //// this supports passing of folder name - currently used by viewmodels and views. //// may not be required if we refactor the item templates to embed the directory. if (createFolder) { ProjectItem folderProjectItem = instance.ProjectItems .Cast <ProjectItem>() .FirstOrDefault(projectItem => projectItem.Name == folderName); //// if the folder doesn't exist create it. if (folderProjectItem == null) { folderProjectItem = instance.ProjectItems.AddFolder(folderName); } projectItems = folderProjectItem.ProjectItems; path = folderProjectItem.Properties.Item("FullPath").Value; } Solution2 solution = instance.DTE.Solution as Solution2; string templatePath = solution.GetProjectItemTemplate(templateName); if (templatePath != null) { string filePath = string.Format(@"{0}\{1}\{2}", path, folderName, fileName); if (File.Exists(filePath) == false) { projectItems.AddFromTemplate(templatePath, fileName); } return(true); } TraceService.WriteError("ProjectExtensions::AddToFolderFromTemplate Cannot find template " + templateName); return(false); }
public void AddFromFile(string fileName,string itemName) { string folderName = GetFolderName(); GetCurrentProject(); viewsFolder = curProject.ProjectItems; ;//default ViewsFolder is the root of the project SearchFolder(folderName, viewsFolder);//find the real folder the new view must be inserted to viewsFolder.AddFromTemplate(fileName, itemName); int i = 1; for (; i < viewsFolder.Count; i++) if (viewsFolder.Item(i).Name == itemName) break; //EnvDTE.Constants.vsViewKindCode = {7651A701-06E5-11D1-8EBD-00A0C90F26EA} viewsFolder.Item(i).Open("{7651A701-06E5-11D1-8EBD-00A0C90F26EA}").Visible = true; }
protected ProjectItem CreateTestProjectItem(ProjectItems projectItems, string templateName) { if (projectItems == null) { throw new ArgumentNullException("projectItems"); } string templateFile = Solution.GetProjectItemTemplate(templateName, this.TargetProject.Language); string itemName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); ProjectItem projectItem = projectItems.AddFromTemplate(templateFile, itemName) ?? projectItems.Cast <ProjectItem>().First(pi => Path.GetFileNameWithoutExtension(pi.Name) == itemName); projectItem.Document.Close(); // To avoid sideffects and enable testing by writing to files as opposed to document manipulation return(projectItem); }
private void CreateAutoMapperProfile(ProjectItems projectItems, CreateMessage model, string classTemplate) { var automapperProfileProjectItem = projectItems.AddFromTemplate(classTemplate, $"{model.AutomapperFileName.FullName}"); (automapperProfileProjectItem.FileCodeModel as FileCodeModel2).AddNotExistingImports(model.DefaultAutoMapperImports); var codeClass = automapperProfileProjectItem.FindCodeClassByName(model.AutomapperFileName.Name); codeClass.Access = vsCMAccess.vsCMAccessPublic; codeClass.InsertInterfaceToTheEnd(model.AutoMapperInterface); codeClass.AddFunction( Name: codeClass.Name, Kind: vsCMFunction.vsCMFunctionConstructor, Type: vsCMTypeRef.vsCMTypeRefVoid, Position: 0, Access: vsCMAccess.vsCMAccessPublic); }
/// <summary> /// Create a new item in the project /// </summary> /// <param name="parent">the parent collection for the new item</param> /// <param name="templateName"></param> /// <param name="language"></param> /// <param name="name"></param> /// <returns></returns> public static ProjectItem AddNewItemFromVsTemplate(ProjectItems parent, string templateName, string language, string name) { if (parent == null) throw new ArgumentException("project"); if (name == null) throw new ArgumentException("name"); DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE)); Solution2 sol = dte.Solution as Solution2; string filename = sol.GetProjectItemTemplate(templateName, language); parent.AddFromTemplate(filename, name); return parent.Item(name); }
//public void CreateFile(string fileName, Template template, IProjectFolder projectFolder) //{ // IProjectFile file = AddNewItemUtil.AddFile(projectFolder, fileName); // if (file == null) return; // ITextControl textControl = EditorManager.GetInstance(file.GetSolution()).OpenProjectFile(file, true); // textControl.WindowModel.Focus(); // //textControl. // //TODO: Fix this R# Mess in order to enable live templates. // //JetBrains.ReSharper.Feature.Services.LiveTemplates.Context.TemplateContextUtil.GetLiveTemplates().ContextFactory. // //IDataContext foo= new DataContext(textControl.); // //JetBrains.ReSharper.Feature.Services.LiveTemplates.FileTemplates.FileTemplatesManager.Instance.CreateFileFromTemplate(foo,template); // //.Intentions.Util.TemplateUtil.ExecuteTemplate(); // //JetBrains.ReSharper.Intentions.Util.TemplateUtil // //LiveTemplatesController.Instance.ExecuteTemplate(projectFolder.GetSolution(), template, textControl); //} public void CreateFile(ISolution solution, ProjectItems projectItems, string fileName, string itemName, string templateName) { string filePath; if (projectItems.Parent is ProjectItem) { filePath = Path.Combine(((ProjectItem)projectItems.Parent).get_FileNames(0), fileName); } else { filePath = Path.Combine(Path.GetDirectoryName(projectItems.ContainingProject.FullName), fileName); } var dteSolution = projectItems.DTE.Solution as Solution2; string templatepath = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "Resources\\" + templateName + "\\ClassUnderTest.vstemplate"); //dteSolution.GetProjectItemTemplate(templateName +".zip", "CSharp"); ProjectItem fileitem = null; projectItems.AddFromTemplate(templatepath, fileName); foreach (ProjectItem item in projectItems) { if (item.Name == fileName) { fileitem = item; break; } } //File.CreateText(filePath).Close(); //ProjectItem fileitem = projectItem.ProjectItems .AddFromFile(filePath); projectItems.ContainingProject.Save(null); var window = fileitem.Open("{7651A701-06E5-11D1-8EBD-00A0C90F26EA}"); window.Close(vsSaveChanges.vsSaveChangesYes); //var progitem = solution.FindProjectItemByLocation(new FileSystemPath(filePath)) as IProjectFile; //ITextControl textControl = EditorManager.GetInstance(solution).OpenProjectFile(progitem, true); ////ITextControl textControl = EditorManager.GetInstance(solution).OpenFile(filePath,true,false); //textControl.WindowModel.Focus(); //bool result = LiveTemplatesController.Instance.ExecuteTemplate(solution, template, textControl); }
public void AddFromFile(string fileName,string itemName) { int rootLen = projectDir.Length; string folderName = viewsFolderName.Substring(rootLen + 1, viewsFolderName.Length - rootLen - 1); int index = GetActiveProject(); if (index > 0) { viewsFolder = dte.Solution.Projects.Item(index).ProjectItems; ;//default ViewsFolder is the root of the project SearchFolder(folderName, viewsFolder);//find the real folder the new view must be inserted to viewsFolder.AddFromTemplate(fileName, itemName); int i = 1; for (; i < viewsFolder.Count; i++) if (viewsFolder.Item(i).Name == itemName) break; //EnvDTE.Constants.vsViewKindCode = {7651A701-06E5-11D1-8EBD-00A0C90F26EA} viewsFolder.Item(i).Open("{7651A701-06E5-11D1-8EBD-00A0C90F26EA}").Visible = true; } }
public void AddNewItemFromVsTemplate(string templateName, string language, string name) { if (name == null) { throw new ArgumentException("name"); } int activeProject = GetActiveProject(); ProjectItems parent = dte.Solution.Projects.Item(activeProject).ProjectItems; if (parent == null) { throw new ArgumentException("project"); } EnvDTE80.Solution2 sol = dte.Solution as EnvDTE80.Solution2; string filename = sol.GetProjectItemTemplate(templateName, language); parent.AddFromTemplate(filename, name); }
public void AddFromFile(string fileName, string itemName) { string folderName = GetFolderName(); GetCurrentProject(); viewsFolder = curProject.ProjectItems;; //default ViewsFolder is the root of the project SearchFolder(folderName, viewsFolder); //find the real folder the new view must be inserted to viewsFolder.AddFromTemplate(fileName, itemName); int i = 1; for (; i < viewsFolder.Count; i++) { if (viewsFolder.Item(i).Name == itemName) { break; } } //EnvDTE.Constants.vsViewKindCode = {7651A701-06E5-11D1-8EBD-00A0C90F26EA} viewsFolder.Item(i).Open("{7651A701-06E5-11D1-8EBD-00A0C90F26EA}").Visible = true; }
/// <summary> /// Create a new item in the project /// </summary> /// <param name="parent">the parent collection for the new item</param> /// <param name="templateName"></param> /// <param name="language"></param> /// <param name="name"></param> /// <returns></returns> public ProjectItem AddNewItemFromVsTemplate(ProjectItems parent, string templateName, string language, string name) { if (parent == null) { throw new ArgumentException("project"); } if (name == null) { throw new ArgumentException("name"); } DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE)); Solution2 sol = dte.Solution as Solution2; string filename = sol.GetProjectItemTemplate(templateName, language); parent.AddFromTemplate(filename, name); return(parent.Item(name)); }
/// <summary> /// Adds the item to folder from template. /// </summary> /// <param name="instance">The instance.</param> /// <param name="templateName">Name of the template.</param> /// <param name="fileName">Name of the file.</param> /// <returns>True or False.</returns> public static bool AddItemToFolderFromTemplate( this Project instance, string templateName, string fileName) { TraceService.WriteLine("ProjectExtensions::AddItemToFolderFromTemplate project=" + instance.Name + " templateName=" + templateName + " fileName=" + fileName); ProjectItems projectItems = instance.ProjectItems; Solution2 solution = instance.DTE.Solution as Solution2; string templatePath = solution.GetProjectItemTemplate(templateName); if (templatePath != null) { projectItems.AddFromTemplate(templatePath, fileName); return(true); } return(false); }
private static void AddFromItemTypeName(Project project, ProjectItems items, string path, string itemTypeName, NewItemDynamicParameters p, Solution2 sln) { if ("folder" == itemTypeName.ToLowerInvariant()) { if (project.Object is SolutionFolder) { var folder = project.Object as SolutionFolder; folder.AddSolutionFolder(path); } else { items.AddFolder(path, Constants.vsProjectItemKindPhysicalFolder); } } else { if (!itemTypeName.ToLowerInvariant().EndsWith(".zip")) { itemTypeName += ".zip"; } p.Category = GetSafeCategoryValue(p.Category, project.CodeModel); //todo: validate p.Category against available item/project tmps if (project.Object is SolutionFolder) { SolutionFolder folder = project.Object as SolutionFolder; NewTemplateItemInSolutionFolder(path, itemTypeName, sln, p, folder); } else { var t = sln.GetProjectItemTemplate(itemTypeName, p.Category); items.AddFromTemplate(t, path); } } }
public void AddFromFile(string fileName, string itemName) { int rootLen = projectDir.Length; string folderName = viewsFolderName.Substring(rootLen + 1, viewsFolderName.Length - rootLen - 1); int index = GetActiveProject(); if (index > 0) { viewsFolder = dte.Solution.Projects.Item(index).ProjectItems;; //default ViewsFolder is the root of the project SearchFolder(folderName, viewsFolder); //find the real folder the new view must be inserted to viewsFolder.AddFromTemplate(fileName, itemName); int i = 1; for (; i < viewsFolder.Count; i++) { if (viewsFolder.Item(i).Name == itemName) { break; } } //EnvDTE.Constants.vsViewKindCode = {7651A701-06E5-11D1-8EBD-00A0C90F26EA} viewsFolder.Item(i).Open("{7651A701-06E5-11D1-8EBD-00A0C90F26EA}").Visible = true; } }
public override void Execute() { string templatefolder = this.SourceFolder; string templateBasePath = GetTemplateBasePath(); if (!Path.IsPathRooted(templatefolder)) { templatefolder = Path.Combine(templateBasePath, templatefolder); } ProjectItems whereToAdd = WhereToAdd(); if (Directory.Exists(templatefolder)) { string[] files = Directory.GetFiles(templatefolder); foreach (string s in files) { string filename = new FileInfo(s).Name; ProjectItem _ProjectItem = whereToAdd.AddFromTemplate(s, filename); } } }
public override void Execute() { DTE vs = base.GetService <DTE>(true); string tempFilename = Path.GetTempFileName(); using (StreamWriter sw = new StreamWriter(tempFilename, false)) { sw.WriteLine(_content); } ProjectItem existingItem = DteHelper.FindItemByName(_targetCollection, _targetFileName, false); if (existingItem != null) { if (overwrite) { OverwriteFile(vs, existingItem.get_FileNames(1), _content); existingItem.Delete(); } } _createdItem = DteHelper.FindItemByName(_targetCollection, _targetFileName, false); if (_createdItem == null) { _createdItem = _targetCollection.AddFromTemplate(tempFilename, _targetFileName); } _createdProjectItems = _createdItem.ProjectItems; if (_open) { Window window = _createdItem.Open("{00000000-0000-0000-0000-000000000000}"); window.Visible = true; window.Activate(); } File.Delete(tempFilename); }
protected ProjectItem CreateTestProjectItem(ProjectItems projectItems, string templateName) { if (projectItems == null) { throw new ArgumentNullException("projectItems"); } string templateFile = Solution.GetProjectItemTemplate(templateName, this.TargetProject.Language); string itemName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); ProjectItem projectItem = projectItems.AddFromTemplate(templateFile, itemName) ?? projectItems.Cast<ProjectItem>().First(pi => Path.GetFileNameWithoutExtension(pi.Name) == itemName); projectItem.Document.Close(); // To avoid sideffects and enable testing by writing to files as opposed to document manipulation return projectItem; }
/// <include file='doc\InstallerDesign.uex' path='docs/doc[@for="InstallerDesign.GetProjectInstallerDocument"]/*' /> /// <devdoc> /// Gets the document that contains the installers for the project. /// </devdoc> public static IDesignerHost GetProjectInstallerDocument(IComponent component) { ProjectItem currentProjItem = (ProjectItem)component.Site.GetService(typeof(ProjectItem)); if (currentProjItem == null) { throw new Exception(SR.GetString(SR.InstallerDesign_CouldntGetService)); } Project project = currentProjItem.ContainingProject; ProjectItems projItems = project.ProjectItems; ProjectItem installationClass = null; string projectKind = project.Kind; string projectInstallerItemName = null; string projectInstallerTemplateName = null; if (new Guid(projectKind).Equals(CSharpProjectGuid)) { // c# has a special name for the installer wizard projectInstallerTemplateName = "\\NewInstaller.vsz"; } else { // all other project types will have the same name projectInstallerTemplateName = "\\Installer.vsz"; } int fileCount = currentProjItem.FileCount; if (fileCount == 0) { throw new Exception(SR.GetString(SR.InstallerDesign_NoProjectFilename)); } string extension = Path.GetExtension(currentProjItem.get_FileNames(0)); projectInstallerItemName = "ProjectInstaller" + extension; try { installationClass = projItems.Item(projectInstallerItemName); } catch (Exception) { // if file isn't in the project, we'll get an ArgumentException. } // If we could't find an existing ProjectInstaller.xx, we'll try to add // one from the template. if (installationClass == null) { string templateFileName = GetItemTemplatesDir(projectKind) + projectInstallerTemplateName; try { // AddFromTemplate will try to copy the template file into ProjectInstaller.xx. // If ProjectInstaller.xx already exists, it will bring up a dialog that says: // A file with the name 'C:\myproject\ProjectInstaller.xx' // already exists. Do you want to replace it? // If you answer yes, you're good to go. The existing file will be overwritten // with the template. If you answer no, AddFromTemplate will throw a COMException // with hresult = 0x80070050 (file already exists). installationClass = projItems.AddFromTemplate(templateFileName, projectInstallerItemName); } catch (COMException e) { // if the errorcode is HRESULT_FROM_WIN32(ERROR_FILE_EXISTS) (which is 0x80070050) // then ProjectInstaller.xx exists and the user does not want to overwrite it. // We could try to use the existing file, but that might cause more problems then // want to get into. Just inform the user that we can't add the installer. if (e.ErrorCode == unchecked ((int)0x80070050)) { throw new Exception(SR.GetString(SR.InstallerDesign_UnableToAddProjectInstaller)); } else { // unexpected -> bubble up throw; } } catch (FileNotFoundException) { // The template was not found. This probably means that the current project type // doesn't provide a template for installers. Nothing to do but report the error. throw new FileNotFoundException(SR.GetString(SR.InstallerDesign_CoulndtFindTemplate), templateFileName); } } try { installationClass.Properties.Item("SubType").Value = "Component"; Window window = installationClass.Open(vsViewKindDesigner); window.Visible = true; IDesignerHost host = (IDesignerHost)window.Object; // make sure the project has a reference to System.Configuration.Install.dll. // This is done as a side-effect of calling GetType. host.GetType(typeof(ComponentInstaller).FullName); return(host); } catch (Exception e) { throw new Exception(SR.GetString(SR.InstallerDesign_CouldntShowProjectInstaller), e); } }
/// <summary> /// Create a new item in the project /// </summary> /// <param name="project">the project collection for the new item</param> /// <param name="templateName"></param> /// <param name="language"></param> /// <param name="name"></param> /// <returns></returns> public ProjectItem AddNewItemFromVsTemplate(ProjectItems project, string templateName, string language, string name) { if (project == null) throw new ArgumentException(nameof(project)); if (name == null) throw new ArgumentException(nameof(name)); var dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE)); var sol = (Solution2) dte.Solution; var filename = sol.GetProjectItemTemplate(templateName, language); project.AddFromTemplate(filename, name); return project.Item(name); }
private ProjectItem OpenOrCreateResourceFile() { ProjectItem resourceFilePrjItem = null; string resourceFileName = null, resourceFileDir = null; if (!m_Settings.IsUseGlobalResourceFile) { resourceFileName = System.IO.Path.ChangeExtension(m_Window.ProjectItem.Name, "Resources.resx"); //file name only resourceFileDir = System.IO.Path.GetDirectoryName(m_Window.ProjectItem.FileNames[0]); } else { resourceFileName = m_ProjectExtension.StartsWith("cs", StringComparison.OrdinalIgnoreCase) ? "Properties" : "My Project"; resourceFileDir = System.IO.Path.GetDirectoryName(m_Window.ProjectItem.ContainingProject.FullName); } //else //get the projects project-items collection ProjectItems prjItems = m_Window.Project.ProjectItems; if (!m_Settings.IsUseGlobalResourceFile) { try { //try to get the parent project-items collection (if in a sub folder) prjItems = ((ProjectItem)m_Window.ProjectItem.Collection.Parent).ProjectItems; } catch { } } //if try { resourceFilePrjItem = prjItems?.Item(resourceFileName); } catch { } if (m_Settings.IsUseGlobalResourceFile) { bool isPropertiesItem = (resourceFilePrjItem != null); if (isPropertiesItem) { prjItems = resourceFilePrjItem.ProjectItems; resourceFilePrjItem = null; resourceFileDir = System.IO.Path.Combine(resourceFileDir, resourceFileName); //append "Properties"/"My Project" because it exists } //if if (prjItems == null) { return(null); //something went terribly wrong that never should have been possible } if (string.IsNullOrEmpty(m_Settings.GlobalResourceFileName)) { resourceFileName = "Resources.resx"; //standard global resource file } else { resourceFileName = System.IO.Path.ChangeExtension(System.IO.Path.GetFileName(m_Settings.GlobalResourceFileName), "Resources.resx"); } try { //searches for the global resource resourceFilePrjItem = prjItems.Item(resourceFileName); } catch { } } //if if (resourceFilePrjItem == null) { #region not in project but file exists? -> ask user if delete string projectPath = System.IO.Path.GetDirectoryName(m_Window.ProjectItem.ContainingProject.FullName), resourceFile = System.IO.Path.Combine(resourceFileDir, resourceFileName), designerFile = System.IO.Path.ChangeExtension(resourceFile, ".Designer." + m_ProjectExtension.Substring(0, 2) /*((m_IsCSharp) ? "cs" : "vb")*/); if (System.IO.File.Exists(resourceFile) || System.IO.File.Exists(designerFile)) { string msg = string.Format("The resource file already exists though it is not included in the project:\r\n\r\n" + "'{0}'\r\n\r\n" + "Do you want to overwrite the existing resource file?", resourceFile.Substring(projectPath.Length).TrimStart('\\')); if (MessageBox.Show(msg, "Make resource", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return(null); } else { TryToSilentlyDeleteIfExistsEvenIfReadOnly(resourceFile); TryToSilentlyDeleteIfExistsEvenIfReadOnly(designerFile); } //else } //if #endregion try { // Retrieve the path to the resource template. string itemPath = ((Solution2)m_Dte2.Solution).GetProjectItemTemplate("Resource.zip", m_ProjectExtension); //create a new project item based on the template /*prjItem =*/ prjItems.AddFromTemplate(itemPath, resourceFileName); //returns always null ... resourceFilePrjItem = prjItems.Item(resourceFileName); } catch (Exception ex) { Trace.WriteLine($"### OpenOrCreateResourceFile() - {ex.ToString()}"); return(null); } } //if if (resourceFilePrjItem == null) { return(null); } //open the ResX file if (!resourceFilePrjItem.IsOpen[EnvDTEConstants.vsViewKindAny]) { resourceFilePrjItem.Open(EnvDTEConstants.vsViewKindDesigner); } return(resourceFilePrjItem); }
public static void AddNewItem(string templateName, string name, string extension, string destinationPath) { var project = GetActiveProject(); if (project != null) { DTE dte = VsAppShell.Current.GetGlobalService <DTE>(); var solution = (Solution2)dte.Solution; // Construct name of the compressed template var compressedTemplateName = Path.ChangeExtension(templateName, "zip"); var templatePath = Path.Combine(GetProjectItemTemplatesFolder(), compressedTemplateName); // We will be extracting template contents into a temp folder var uncompressedTemplateFolder = Path.Combine(Path.GetTempPath(), templateName); var uncompressedTemplateName = Path.ChangeExtension(compressedTemplateName, "vstemplate"); var tempTemplateFile = Path.Combine(uncompressedTemplateFolder, uncompressedTemplateName); // Extract template files overwriting any existing ones using (ZipArchive zip = ZipFile.OpenRead(templatePath)) { foreach (ZipArchiveEntry entry in zip.Entries) { if (!Directory.Exists(uncompressedTemplateFolder)) { Directory.CreateDirectory(uncompressedTemplateFolder); } string destFilePath = Path.Combine(uncompressedTemplateFolder, entry.FullName); if (!string.IsNullOrEmpty(entry.Name)) { entry.ExtractToFile(destFilePath, true); } else { Directory.CreateDirectory(Path.GetDirectoryName(destFilePath)); } } // Given path to the project or a folder in it, generate unique file name var fileName = GetUniqueFileName(destinationPath, name, extension); // Locate folder in the project var projectFolder = Path.GetDirectoryName(project.FullName); if (destinationPath.StartsWith(projectFolder, StringComparison.OrdinalIgnoreCase)) { ProjectItems projectItems = project.ProjectItems; if (destinationPath.Length > projectFolder.Length) { var relativePath = destinationPath.Substring(projectFolder.Length + 1); // Go into folders and find project item to insert the file in while (relativePath.Length > 0) { int index = relativePath.IndexOf('\\'); string folder; if (index >= 0) { folder = relativePath.Substring(0, index); relativePath = relativePath.Substring(index + 1); } else { folder = relativePath; relativePath = string.Empty; } try { var item = projectItems.Item(folder); projectItems = item.ProjectItems; } catch (COMException) { return; } } } projectItems?.AddFromTemplate(tempTemplateFile, Path.GetFileName(fileName)); } } } }
internal static ProjectItem AddFromTemplate(ProjectItems projectItems, string template, string TargetFileName, bool overwrite) { ProjectItem pitem = null; try { //is there already a project item with the target name ProjectItem existingItem = GetProjectItemByName(projectItems, TargetFileName); if (existingItem != null) { //item with the same name already there //overwrite it? if (overwrite || projectItems.DTE.SuppressUI) { //overwrite the file with the new contents string pathToExistingItem = Helpers.GetFullPathOfProjectItem(existingItem); Helpers.EnsureCheckout(projectItems.DTE, pathToExistingItem); File.Copy(template, pathToExistingItem, true); Helpers.LogMessage(projectItems.DTE, projectItems.DTE, pathToExistingItem + ": Contents updated"); } else { if (MessageBox.Show("File " + TargetFileName + " already exists. Overwrite?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes) { //overwrite the file with the new contents string pathToExistingItem = Helpers.GetFullPathOfProjectItem(existingItem); Helpers.EnsureCheckout(projectItems.DTE, pathToExistingItem); File.Copy(template, pathToExistingItem, true); Helpers.LogMessage(projectItems.DTE, projectItems.DTE, pathToExistingItem + ": Contents updated"); } } return existingItem; } //is there already a file with the same name, but it is not part of the project string pathToExistingFile = Path.Combine(GetPathOfProjectItems(projectItems), TargetFileName); if (File.Exists(pathToExistingFile)) { //ups, file with same name exists, but is not part of the project //update the contents and include the file to the project Helpers.EnsureCheckout(projectItems.DTE, pathToExistingFile); File.Copy(template, pathToExistingFile, true); return Helpers.AddFromFile(projectItems, pathToExistingFile); } //default situation: a file or item with the same name does not exists at the target location pitem = projectItems.AddFromTemplate(template, TargetFileName); // Helpers.LogMessage(projectItems.DTE, projectItems.DTE, Helpers.GetFullPathOfProjectItem(pitem) + ": File Added"); Helpers.CheckSharePointReferences(pitem); } catch (Exception) { Helpers.LogMessage(projectItems.DTE, projectItems.DTE, Helpers.GetFullPathOfProjectItem(pitem) + ": Already exists"); } return pitem; }
/// <summary> /// Generates the specified Source File in the received Project with the options /// provided and gets the Namespace ready to add code in it. /// </summary> /// <param name="targetProject">Project where the Source File is going to be placed.</param> /// <param name="targetProjectFolder">Project folder where the source file is going to be placed. /// Null indicates to place the source file as child of targetProject.</param> /// <param name="sourceFileName">Source File name to use.</param> /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param> /// <param name="sourceNamespace">Namespace used in the Source File.</param> /// <param name="isServiceReady">Specifies if it is Service-Ready (serialization is going to be used).</param> /// <param name="sourceFileItem">(out parameter) Source File ProjectItem.</param> /// <returns></returns> public static CodeNamespace GenerateSourceAndGetNamespace(Project targetProject, ProjectItem targetProjectFolder, string sourceFileName, string sourceFileHeaderComment, string sourceNamespace, bool isServiceReady, out ProjectItem sourceFileItem) { // Validate source file name if (sourceFileName.EndsWith(Resources.CSharpFileExtension) == false) { sourceFileName += Resources.CSharpFileExtension; } // Validate source file header comment if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false) { if (sourceFileHeaderComment.IndexOf("*/") >= 0) { throw new ApplicationException(Resources.Error_HeaderCommentInvalidChars); } } // ProjectItems collection where to place the source file ProjectItems projectItems = targetProject.ProjectItems; if (targetProjectFolder != null) { // Place inside received project folder projectItems = targetProjectFolder.ProjectItems; } // Properties collection of the target EnvDTE.Properties targetProperties = targetProject.Properties; if (targetProjectFolder != null) { targetProperties = targetProjectFolder.Properties; } // Source file sourceFileItem = null; #region If source file exists in the target, clear it and get the reference foreach (ProjectItem projItem in projectItems) { string projItemFileName = projItem.Properties.Item(Resources.ProjectItem_FileName).Value.ToString(); if (sourceFileName.ToLower() == projItemFileName.ToLower()) { // Source file already exists sourceFileItem = projItem; if (sourceFileItem.FileCodeModel.CodeElements != null && sourceFileItem.FileCodeModel.CodeElements.Count > 0) { // Clear source file CodeElement firstElement = sourceFileItem.FileCodeModel.CodeElements.Item(1); CodeElement lastElement = sourceFileItem.FileCodeModel.CodeElements.Item( sourceFileItem.FileCodeModel.CodeElements.Count); EditPoint startPoint = firstElement.StartPoint.CreateEditPoint(); EditPoint endPoint = lastElement.EndPoint.CreateEditPoint(); while (startPoint.AtStartOfDocument != true) { startPoint.LineUp(); } while (endPoint.AtEndOfDocument != true) { endPoint.LineDown(); } startPoint.Delete(endPoint); } break; } } #endregion #region If source file NOT exists in the target, create it and get the reference if (sourceFileItem == null) { // New source file, get target path string targetPath = targetProperties.Item(Resources.Properties_LocalPath).Value.ToString(); // Check if the new source file already exists in the file system (and it is not added to the solution) if (File.Exists(targetPath + sourceFileName)) { // Rename the existent source file string backupSourceFileName = (sourceFileName + Resources.BackupFileExtension); File.Move((targetPath + sourceFileName), (targetPath + backupSourceFileName)); // Add warning VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning, string.Format(Resources.Warning_SourceFileAlreadyExists, sourceFileName, backupSourceFileName), targetProject, sourceFileName, null, null); } // Add source file to target sourceFileItem = projectItems.AddFromTemplate(TemplateClass.FilePath, sourceFileName); } #endregion #region Generate imports var importList = new List <SourceCodeImport>(); importList.Add(new SourceCodeImport(Resources.NamespaceSystem)); importList.Add(new SourceCodeImport(Resources.NamespaceSystemCollectionsGeneric)); importList.Add(new SourceCodeImport(Resources.NamespaceSystemText)); if (isServiceReady) { importList.Add(new SourceCodeImport(Resources.NamespaceSystemRuntimeSerialization)); } importList = importList.OrderBy(d => d.ImportNamespace).ToList(); #endregion Generate imports // Add imports to the source code VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList); // Get Source file code start EditPoint objEditPoint = sourceFileItem.FileCodeModel.CodeElements.Item(1).StartPoint.CreateEditPoint(); objEditPoint.StartOfDocument(); // Add header comment if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false) { sourceFileHeaderComment = (Environment.NewLine + sourceFileHeaderComment + Environment.NewLine); objEditPoint.Insert( string.Format(Resources.CSharpCommentMultiline, sourceFileHeaderComment) + Environment.NewLine); } // Add EntitiesToDTOs signature string timestamp = DateTime.Now.ToString("yyyy/MM/dd - HH:mm:ss"); objEditPoint.Insert(string.Format(Resources.EntitiesToDTOsSignature, AssemblyHelper.Version, timestamp)); objEditPoint.Insert(Environment.NewLine); // Add blank line before source file namespace objEditPoint.EndOfDocument(); objEditPoint.Insert(Environment.NewLine); // Add namespace CodeNamespace objNamespace = sourceFileItem.FileCodeModel .AddNamespace(sourceNamespace, AppConstants.PLACE_AT_THE_END); return(objNamespace); }