private string ResolveAppNameCollisionWithUser(EnvDTE.ProjectItems items, string name, out bool cancel) { while (true) { try { if (items.Item(name) == null) { break; } } catch (ArgumentException) { break; } var td = new TaskDialog(new ServiceProvider(GetSite())) { Title = Resources.ProductTitle, MainInstruction = string.Format(Resources.DjangoAppAlreadyExistsTitle, name), Content = string.Format(Resources.DjangoAppAlreadyExistsInstruction, name), AllowCancellation = true }; var cont = new TaskDialogButton( Resources.DjangoAppAlreadyExistsCreateAnyway, Resources.DjangoAppAlreadyExistsCreateAnywaySubtitle ); var retry = new TaskDialogButton(Resources.SelectAnotherName); td.Buttons.Add(cont); td.Buttons.Add(retry); td.Buttons.Add(TaskDialogButton.Cancel); var clicked = td.ShowModal(); if (clicked == cont) { break; } else if (clicked == retry) { name = GetNewAppNameFromUser(name); if (string.IsNullOrEmpty(name)) { cancel = true; return(null); } } else { cancel = true; return(null); } } cancel = false; return(name); }
private IEnumerable <EnvDTE.ProjectItem> GetProjectItems(EnvDTE.ProjectItems projectItems) { List <EnvDTE.ProjectItem> result = new List <EnvDTE.ProjectItem>(); int itemCount = TryHelper.Run(() => projectItems.Count); for (int i = 0; i < itemCount; i++) { result.Add(TryHelper.Run(() => projectItems.Item(i + 1))); } return(result); }
static bool DeleteFileInProject(EnvDTE.Project project, string fileName) { EnvDTE.ProjectItems projectItems = project.ProjectItems; try { projectItems.Item(fileName).Delete(); return(true); } catch (Exception ex) { DisplayMessageBoxOnUIThread(string.Format("Unable to delete '{0}'.", fileName) + Environment.NewLine + Environment.NewLine + ex.ToString()); return(false); } }
private static EnvDTEProjectItem GetProjectItem(EnvDTEProjectItems envDTEProjectItems, string name, IEnumerable <string> allowedItemKinds) { try { EnvDTEProjectItem envDTEProjectItem = envDTEProjectItems.Item(name); if (envDTEProjectItem != null && allowedItemKinds.Contains(envDTEProjectItem.Kind, StringComparer.OrdinalIgnoreCase)) { return(envDTEProjectItem); } } catch { } return(null); }
private static EnvDTE.ProjectItem GetProjectItem(EnvDTE.ProjectItems envDTEProjectItems, string name, IEnumerable <string> allowedItemKinds) { Debug.Assert(ThreadHelper.CheckAccess()); try { EnvDTE.ProjectItem envDTEProjectItem = envDTEProjectItems.Item(name); if (envDTEProjectItem != null && allowedItemKinds.Contains(envDTEProjectItem.Kind, StringComparer.OrdinalIgnoreCase)) { return(envDTEProjectItem); } } catch { } return(null); }
/// <summary> /// Find all .cs files in the project, including sub-folders. /// </summary> private void findFiles(EnvDTE.ProjectItems projectItems, HashSet <FileInfo> files) { // We look through the items... int numProjectItems = Utils.call(() => (projectItems.Count)); for (int i = 1; i <= numProjectItems; ++i) { EnvDTE.ProjectItem projectItem = Utils.call(() => (projectItems.Item(i))); // We get the full-path... EnvDTE.Properties dteProperties = Utils.call(() => (projectItem.Properties)); Dictionary <string, object> properties = getProperties(dteProperties); string fullPath = getStringProperty(properties, "FullPath"); int copyToOutputFolder = getIntProperty(properties, "CopyToOutputDirectory"); // We check if it is a file (it could be a folder instead)... if (File.Exists(fullPath) == true) { // We add it to the list of files... FileInfo fileInfo = new FileInfo(); fileInfo.AbsolutePath = fullPath; fileInfo.RelativePath = Utils.makeRelativePath(m_projectInfo.RootFolderAbsolute, fullPath); fileInfo.CopyToOutputFolder = (copyToOutputFolder != 0); files.Add(fileInfo); } // We see if the item itself has sub-items... EnvDTE.ProjectItems subItems = Utils.call(() => (projectItem.ProjectItems)); if (subItems != null) { findFiles(subItems, files); } // We see if this item has a sub-project... EnvDTE.Project subProject = Utils.call(() => (projectItem.SubProject)); if (subProject != null) { EnvDTE.ProjectItems subProjectItems = Utils.call(() => (subProject.ProjectItems)); findFiles(subProjectItems, files); } } }
/// <summary> /// Parses a collection of project-items checking for sub-projects. /// </summary><remarks> /// Project items can be things like files and folders, or sub-projects. /// So when we parse a project, we need to drill into the items as there /// may be projects nested inside folders etc. /// </remarks> private void parseProjectItems(EnvDTE.ProjectItems projectItems) { // We look through the items... int numProjectItems = Utils.call(() => (projectItems.Count)); for (int i = 1; i <= numProjectItems; ++i) { EnvDTE.ProjectItem projectItem = Utils.call(() => (projectItems.Item(i))); // We see if the item itself has sub-items... EnvDTE.ProjectItems subItems = Utils.call(() => (projectItem.ProjectItems)); if (subItems != null) { parseProjectItems(subItems); } // We see if this item has a sub-project... EnvDTE.Project subProject = Utils.call(() => (projectItem.SubProject)); if (subProject != null) { parseProject(subProject); } } }
/// <summary> /// ValidProjectItems recursively travels down the tree of items provided by /// the projectitems, checking for validity. This check is here to ensure that /// users to not attempt to copy projects that contain file types that would /// require hard path references or for us to otherwise have to perform /// complex transformations on the project structure on-disk to copy it. /// </summary> /// <param name="Items"> The ProjectItems to recursively check.</param> /// <param name="strProjectRootPath"> The upper-case version of the root of the project path.</param> private bool ValidProjectItems(EnvDTE.ProjectItems Items, string strProjectRootPath) { EnvDTE.ProjectItem Item = null; int i, j, nItemCount, nFileCount; string strFilePath, strFileKind; nItemCount = Items.Count; for (i = 1; i <= nItemCount; i++) { Item = Items.Item(i); nFileCount = Item.FileCount; for (j = 1; j <= nFileCount; j++) { strFilePath = Item.get_FileNames((short)j); strFilePath = strFilePath.ToUpper(); strFileKind = Item.Kind; if ((strFileKind == EnvDTE.Constants.vsProjectItemKindPhysicalFile) || (strFileKind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)) { if (!strFilePath.StartsWith(strProjectRootPath)) { return(false); } } else if ((strFileKind == EnvDTE.Constants.vsProjectItemKindSubProject) || (strFileKind == EnvDTE.Constants.vsProjectItemKindVirtualFolder) || (strFileKind == EnvDTE.Constants.vsProjectItemKindMisc) || (strFileKind == EnvDTE.Constants.vsProjectItemKindSolutionItems)) { // Do nothing. We leave these kinds of items alone. } else if ((new System.IO.FileInfo(strFilePath)).Exists) { // If we fall down to this branch or further, it means that the package-provider // did not follow the specifications for exposing items through the object model. // However, since we cannot guarantee compliance, we must support this behavior. if (!strFilePath.StartsWith(strProjectRootPath)) { return(false); } } else if ((new System.IO.DirectoryInfo(strFilePath).Exists)) { try { if (!ValidProjectItems(Item.ProjectItems, strProjectRootPath)) { return(false); } } catch (Exception /*e*/) { // Falling into here means that though the directory exists // on disk, it isn't necessarily holding any files. Some // project types also enumerate all of the files + all of // the directories as ProjectItems, rather than nesting // them in the more intuitive way. We must support both. } } // Otherwise, it's some kind of 'virtual object' and will be ignored // during the copying process, since it's probably built into the // settings in the project file anyway. } } return(true); }
/// <summary> /// Loops through each of the items in the project, attempting to extract any sections of code /// marked. /// </summary> /// <param name="dte"> Pointer to Object Model in which all actions should be performed </param> private bool ExtractItems(EnvDTE.ProjectItems projSourceItems, EnvDTE._DTE dte, EnvDTE.ProjectItems projDestItems) { EnvDTE.ProjectItem projItem = null; EnvDTE.TextDocument textDoc = null; EnvDTE.Properties extractorProperties = null; Extensions extensions = null; CommentPair comments = null; EnvDTE.Window w = null; bool fSuccess = true; int i, nItems, nLastIndex; string strExtension; extractorProperties = m_application.get_Properties("Assignment Manager", "Code Extractor"); if (extractorProperties == null) { throw new Exception("The Academic Code Extractor is not properly installed and configured."); } extensions = extractorProperties.Item("Extensions").Object as Extensions; if (extensions == null) { throw new Exception("The Academic Code Extractor is not properly installed and configured."); } nItems = projDestItems.Count; for (i = 1; i <= nItems; i++) { projItem = projDestItems.Item(i); try { if (projItem.ProjectItems.Count > 0) { ExtractItems(projSourceItems.Item(i).ProjectItems, dte, projItem.ProjectItems); } // Note that this will *actually* be happening in an invisible // out-of-process instance of VS, so the user will not be // subjected to appearing / disappearing windows. w = projItem.Open(EnvDTE.Constants.vsViewKindTextView); textDoc = w.Document.Object("TextDocument") as EnvDTE.TextDocument; strExtension = projItem.get_FileNames(1); nLastIndex = strExtension.LastIndexOf('.'); if (nLastIndex == -1) { w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); continue; // We have no capacity for files with no extension. } strExtension = strExtension.Remove(0, nLastIndex + 1); // Trim off the 'name.' part of 'name.ext' comments = extensions[strExtension]; if (comments == null) { w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); continue; // This file has no associated extension type. Ignore it. } fSuccess &= ExtractText(textDoc, comments.BeginComment, comments.EndComment, projSourceItems); w.Close(EnvDTE.vsSaveChanges.vsSaveChangesYes); } catch (Exception /*e*/) { // If we end up here, that simply means that the file // has no text. Since we obviously don't want to remove the // textual tags from a file with no comments... if (w != null) { w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); } } } return(fSuccess); }
/// <summary> /// This handles the low-level copying of files from a project into a destination path, flattening /// the file structure. /// </summary> private static bool CopyProjectFiles(EnvDTE.Project proj, string destPath, string listingFile) { System.IO.StreamWriter writer = null; EnvDTE.ProjectItems Items = proj.ProjectItems; EnvDTE.ProjectItem Item = null; int i, j, nItemCount, nFileCount; string strFileName = null; string strFilePath = null; bool fSucceeded = true; try { // Open for append writer = new System.IO.StreamWriter(listingFile, true); nItemCount = Items.Count; for (i = 1; i <= nItemCount; i++) { Item = Items.Item(i); nFileCount = Item.FileCount; for (j = 1; j <= nFileCount; j++) { strFilePath = Item.get_FileNames((short)j); // NOTE: The item kind can be one of physical file, misc item, // or solution item. However, since we're explicitly *in* the // misc or solution items folders if we're here, it makes more // sense just to copy any & all files that we find in the folder // and are able to locate on disk. // The only exception is HTTP-based URLs, which we explicitly // pick out and add to the listing file, which is deployed // with all submitted assignments. if ((new System.IO.FileInfo(strFilePath)).Exists) { strFileName = strFilePath.Substring(System.Math.Max(strFilePath.LastIndexOf('/'), strFilePath.LastIndexOf('\\'))); System.IO.File.Copy(strFilePath, destPath + strFileName); writer.WriteLine(strFileName); } else { if (strFilePath.ToUpper().StartsWith("HTTP://")) { writer.WriteLine(strFilePath); } } } } } catch (System.Exception) { fSucceeded = false; } finally { if (writer != null) { writer.Close(); } } return(fSucceeded); }
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) { // Delete the removed items from the project if (_removedItems != null) { EnvDTE.ProjectItems subItems = _projectItem.ProjectItems; foreach (string itemName in _removedItems.Keys) { try { EnvDTE.ProjectItem subItem = subItems.Item(itemName); if (subItem != null) { subItem.Delete(); } } catch (ArgumentException) { // Swallow } } } // throw away the original build item group if (_originalItemGroup != null) { try { #if VISUALSTUDIO_10_0 _project.RemoveChild(_originalItemGroup); #else _project.RemoveItemGroup(_originalItemGroup); #endif } catch (InvalidOperationException) { // Swallow } } #if VISUALSTUDIO_10_0 Dictionary <string, ProjectItemElement> removeItems = new Dictionary <string, ProjectItemElement>(); #else Dictionary <string, BuildItem> removeItems = new Dictionary <string, BuildItem>(); #endif string tmpFile = null; try { EnvDTE.ProjectItems projectItems = _projectItem.ProjectItems; #if VISUALSTUDIO_10_0 string itemDirectory = (new FileInfo((string)_project.FullPath)).DirectoryName; foreach (ProjectItemElement item in _itemGroup.Items) #else string itemDirectory = (new FileInfo((string)_project.FullFileName)).DirectoryName; foreach (BuildItem item in this._itemGroup) #endif { string filePath = string.Concat(itemDirectory, Path.DirectorySeparatorChar, item.Include); string fileName = (new FileInfo(item.Include)).Name; if (File.Exists(filePath)) { try { projectItems.AddFromFile(filePath); } catch (ArgumentException) { // Swallow } } else { if (tmpFile == null) { tmpFile = Path.GetTempFileName(); } EnvDTE.ProjectItem projectItem = projectItems.AddFromTemplate(tmpFile, fileName); string customTool = item.GetMetadata(ITEMMETADATA_GENERATOR); if (!string.IsNullOrEmpty(customTool)) { projectItem.Properties.Item("CustomTool").Value = customTool; } } removeItems[item.Include] = null; } } finally { if (tmpFile != null) { File.Delete(tmpFile); } } #if VISUALSTUDIO_10_0 foreach (ProjectItemGroupElement group in this._project.ItemGroups) #else foreach (BuildItemGroup group in this._project.ItemGroups) #endif { if (group.Condition.Trim() == this._itemGroup.Condition.Trim()) { continue; } #if VISUALSTUDIO_10_0 foreach (ProjectItemElement item in group.Items) #else foreach (BuildItem item in group) #endif { if (removeItems.ContainsKey(item.Include)) { removeItems[item.Include] = item; } } } foreach (string key in removeItems.Keys) { #if VISUALSTUDIO_10_0 ProjectItemElement removeItem; ProjectElementContainer removeFrom; if (null != (removeItem = removeItems[key]) && null != (removeFrom = removeItem.Parent)) { removeFrom.RemoveChild(removeItem); } #else BuildItem removeItem = removeItems[key]; if (removeItem != null) { _project.RemoveItem(removeItem); } #endif } VSLangProj.VSProjectItem vsProjectItem = _projectItem.Object as VSLangProj.VSProjectItem; if (vsProjectItem != null) { vsProjectItem.RunCustomTool(); } } else { #if VISUALSTUDIO_10_0 _project.RemoveChild(_itemGroup); #else _project.RemoveItemGroup(_itemGroup); #endif } base.OnClosed(e); }