private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable <String> keepFileNames) { var keepFileNameSet = new HashSet <String>(keepFileNames); var projectFiles = new Dictionary <String, EnvDTE.ProjectItem>(); var originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.get_FileNames(0)) + "."; foreach (EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) { projectFiles.Add(projectItem.get_FileNames(0), projectItem); } // Remove unused items from the project foreach (var pair in projectFiles) { if (!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix)) { pair.Value.Delete(); } } // Add missing files to the project foreach (String fileName in keepFileNameSet) { if (!projectFiles.ContainsKey(fileName)) { templateProjectItem.ProjectItems.AddFromFile(fileName); } } }
/// <summary> /// See <see cref="IWizard"/>. /// </summary> /// <param name="projectItem">See Visual Studio SDK documentation.</param> public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem) { if (projectItem == null) { throw new ArgumentNullException("projectItem"); } this.forward.ProjectItemFinishedGenerating(projectItem.get_FileNames(0)); }
private static Configuration GetDesignTimeConfig() { ExeConfigurationFileMap configMap = null; Configuration config = null; String path = null; // Get an instance of the currently running Visual Studio IDE. EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.9.0"); if (dte != null) { dte.SuppressUI = true; EnvDTE.ProjectItem item = dte.Solution.FindProjectItem("web.config"); if (item != null) { if (!item.ContainingProject.FullName.ToLower().StartsWith("http:")) { System.IO.FileInfo info = new System.IO.FileInfo(item.ContainingProject.FullName); path = String.Format("{0}\\{1}", info.Directory.FullName, item.Name); configMap = new ExeConfigurationFileMap(); configMap.ExeConfigFilename = path; } else { configMap = new ExeConfigurationFileMap(); configMap.ExeConfigFilename = item.get_FileNames(0); } } /* * Array projects = (Array) dte2.ActiveSolutionProjects; * EnvDTE.Project project = (EnvDTE.Project) projects.GetValue(0); * System.IO.FileInfo info; * * foreach ( EnvDTE.ProjectItem item in project.ProjectItems ) * { * if ( String.Compare(item.Name, "web.config", true) == 0 ) * { * info = new System.IO.FileInfo(project.FullName); * path = String.Format("{0}\\{1}", info.Directory.FullName, item.Name); * configMap = new ExeConfigurationFileMap(); * configMap.ExeConfigFilename = path; * break; * } * } */ } config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); return(config); }
/// <summary> /// Retrieves the connection strings section from the given project. /// </summary> public static ConnectionStringsSection GetSection(EnvDTE.Project project) { if (project == null) { return(null); } EnvDTE.ProjectItem configItem = null; //string configName; //if (DteHelper.IsWebProject(project)) //{ // configName = "Web.config"; //} //else //{ // configName = "App.config"; //} //configItem = DteHelper.FindItemByName(project.ProjectItems, configName, false); //if (configItem == null) //{ // configItem = DteHelper.FindItemByName(project.ProjectItems, configName.ToLowerInvariant(), false); //} if (DteHelper.IsWebProject(project)) { try { configItem = FindItemByName(project.ProjectItems, "web.config", true); } catch { //With Web projects without any subfolder this method throws an exception configItem = FindItemByName(project.ProjectItems, "web.config", false); } } else { configItem = FindItemByName(project.ProjectItems, "app.config", true); } if (configItem == null) { return(null); } string configFile = configItem.get_FileNames(1); return(GetSection(configFile)); }
private void ProjectItemRemoved(EnvDTE.ProjectItem projectItem) { try { CodeIssues.RemoveAll(new CodeIssueMatch(projectItem.get_FileNames(0)).FilePathMatch); } catch (Exception err) { Debug.Assert(false, "Error removing code issues", err.Message); } OnResults(null); }
private bool GetProjectItemId(IVsHierarchy projectHierarchy, EnvDTE.ProjectItem projectItem, out uint projectItemId) { projectItemId = 0; string projectItemName = null; try { projectItemName = projectItem.get_FileNames(0); } catch { } if (string.IsNullOrEmpty(projectItemName)) { return(false); } if (projectHierarchy.ParseCanonicalName(projectItemName, out projectItemId) != 0) { return(false); } return(true); }
/// <summary> /// Provides the list of valid values to choose from for the connection string. /// </summary> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { ConnectionStringsSection section = null; if (String.IsNullOrEmpty(configurationArgument)) { EnvDTE.DTE vs = (EnvDTE.DTE)context.GetService(typeof(EnvDTE.DTE)); if (vs == null) { return(new StandardValuesCollection(null)); } EnvDTE.Project project = DteHelper.GetSelectedProject(vs); if (project == null) { return(new StandardValuesCollection(null)); } section = ConnectionSettingsInfo.GetSection(vs); } else { IDictionaryService dictionary = (IDictionaryService)context.GetService(typeof(IDictionaryService)); EnvDTE.ProjectItem configurationItem = dictionary.GetValue(configurationArgument) as EnvDTE.ProjectItem; if (configurationItem != null) { section = ConnectionSettingsInfo.GetSection(configurationItem.get_FileNames(1)); } } if (section == null) { return(new StandardValuesCollection(null)); } List <ConnectionStringSettings> connectionslist = new List <ConnectionStringSettings>(section.ConnectionStrings.Count); foreach (ConnectionStringSettings setting in section.ConnectionStrings) { connectionslist.Add(setting); } connectionslist.Sort(CompareConnectionStringSettings); return(new StandardValuesCollection(connectionslist)); }
private void ProjectItemRenamed(EnvDTE.ProjectItem projectItem, string oldName) { try { string originalPath = Path.GetDirectoryName(projectItem.get_FileNames(0)) + Path.DirectorySeparatorChar + oldName; foreach (CodeIssueFile codeIssue in CodeIssues) { if (codeIssue.file.Name == originalPath) { codeIssue.file = GetSourceFile(projectItem); } } } catch (Exception err) { Debug.Assert(false, "Error renaming code issues", err.Message); } OnResults(null); }
private void OnItemRenamed(EnvDTE.ProjectItem projItem, string oldName) { this.Output(string.Format("[Event] Renamed {0} to {1} in project {2}\n", oldName, Path.GetFileName(projItem.get_FileNames(1)), projItem.ContainingProject.Name)); }
/// <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); }
/// <summary> /// Return a sorted array of loaded extensions /// </summary> public string[] GetLoadedExtensions(IServiceProvider serviceProvider) { string[] retVal = myLoadedExtensions; if (retVal == null) { if (myDocument == null && myProjectItem != null) { myDocument = myProjectItem.Document; } object documentExtensionManager; MethodInfo methodInfo; string itemPath = null; if (null != myDocument && null != (documentExtensionManager = ORMCustomToolUtility.GetDocumentExtension <object>(myDocument, "ORMExtensionManager", itemPath = myProjectItem.get_FileNames(0), serviceProvider)) && null != (methodInfo = documentExtensionManager.GetType().GetMethod("GetLoadedExtensions", Type.EmptyTypes))) { retVal = methodInfo.Invoke(documentExtensionManager, null) as string[]; myDocument = null; // No longer needed } Stream stream = null; if (null == retVal) { // First used the passed in stream stream = myStream; // Next use an open text document. Note that this will already have provided // an extension manager if this is an open ORM designer if (stream == null && myDocument != null) { EnvDTE.TextDocument textDoc = ORMCustomToolUtility.GetDocumentExtension <EnvDTE.TextDocument>(myDocument, "TextDocument", itemPath ?? (itemPath = myProjectItem.get_FileNames(0)), serviceProvider); if (textDoc != null) { // Note that the stream will be closed with the default reader settings of the XmlReader below stream = new MemoryStream(Encoding.UTF8.GetBytes(textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint)), false); } } // Try the file directly from the project item if (stream == null && myProjectItem != null) { // Note that the stream will be closed with the default reader settings of the XmlReader below stream = new FileStream(myProjectItem.get_FileNames(0), FileMode.Open); } } if (stream != null) { // Attempt to open the stream as an Xml file to // get the required extensions from the Xml string[] namespaces = null; int namespaceCount = 0; try { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; using (XmlReader reader = XmlReader.Create(stream, readerSettings)) { reader.MoveToContent(); if (reader.NodeType == XmlNodeType.Element) { int attributeCount = reader.AttributeCount; if (attributeCount != 0) { namespaces = new string[attributeCount]; if (reader.MoveToFirstAttribute()) { do { if (reader.Prefix == "xmlns" || reader.Name == "xmlns") { // Note that some of these are standard, not extensions, but it // isn't worth the trouble to add extra ORM knowledge here to figure it out string value = reader.Value; if (!string.IsNullOrEmpty(value)) { namespaces[namespaceCount] = reader.Value; ++namespaceCount; } } } while (reader.MoveToNextAttribute()); } } } } } catch (XmlException) { // Nothing to do } finally { if (myStream != null) { myStream.Seek(0, SeekOrigin.Begin); myStream = null; } } if (namespaceCount != 0) { if (namespaceCount != namespaces.Length) { Array.Resize(ref namespaces, namespaceCount); } retVal = namespaces; } } if (retVal == null) { retVal = new string[0]; } else { Array.Sort <string>(retVal); } myLoadedExtensions = retVal; } return(retVal); }
/// <summary> /// Ensure that the current project item has the required extensions loaded. /// This is only called after verifying that the current project item does /// not satisfy the requirements. /// </summary> /// <param name="projectItem">The <see cref="EnvDTE.ProjectItem"/> to modify</param> /// <param name="serviceProvider">The <see cref="IServiceProvider"/> for document tracking.</param> /// <param name="extensions">An <see cref="T:ICollection{System.String}"/> of additional required extensions</param> public static bool EnsureExtensions(EnvDTE.ProjectItem projectItem, IServiceProvider serviceProvider, ICollection <string> extensions) { ServiceProvider provider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)projectItem.DTE); // UNDONE: Localize message strings in here if ((int)DialogResult.No == VsShellUtilities.ShowMessageBox( provider, "Additional extensions are required to support the chosen generators. Would you like to load the required extensions now?", "ORM Generator Selection", OLEMSGICON.OLEMSGICON_QUERY, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST)) { return(false); } EnvDTE.Document document = projectItem.Document; bool secondPass = false; bool tryDocument = true; string itemPath = null; while (tryDocument) { object documentExtensionManager; MethodInfo methodInfo; if (null != document && null != (documentExtensionManager = ORMCustomToolUtility.GetDocumentExtension <object>(document, "ORMExtensionManager", itemPath ?? (itemPath = projectItem.get_FileNames(0)), serviceProvider)) && null != (methodInfo = documentExtensionManager.GetType().GetMethod("EnsureExtensions", new Type[] { typeof(string[]) }))) { string[] extensionsArray = new string[extensions.Count]; extensions.CopyTo(extensionsArray, 0); methodInfo.Invoke(documentExtensionManager, new object[] { extensionsArray }); return(true); } if (secondPass) { return(false); } tryDocument = false; secondPass = true; // UNDONE: Localize message strings in here if ((int)DialogResult.No == VsShellUtilities.ShowMessageBox( provider, "The .ORM file must be open in the default designer to add extensions. Would you like to open or reopen the document now?", "ORM Generator Selection", OLEMSGICON.OLEMSGICON_QUERY, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST)) { return(false); } if (document != null) { document.Close(EnvDTE.vsSaveChanges.vsSaveChangesPrompt); document = projectItem.Document; } if (document == null) { projectItem.Open(Guid.Empty.ToString("B")).Visible = true; document = projectItem.Document; tryDocument = true; } } return(false); }
private static SourceFile GetSourceFile(EnvDTE.ProjectItem projectItem) { return(CodeRush.Source.ActiveSolution.FindSourceFile(projectItem.get_FileNames(0))); }