public string sourceprefix(TreeNode node) { string prefix = ""; VSProjectItem pp = GetVSProjectItem(node); string include = pp.Include; if (include != null) { string[] cc = include.Split("\\".ToCharArray()); if (cc.Length == 1) { return(prefix); } string last = cc[cc.Length - 1]; string name = include.Replace("\\" + last, ""); prefix = name; } return(prefix); }
private static void FindProjectItemDependents(ProjectItem item, List <ProjectItem> toProcess) { VSProjectItem item2 = item.Object as VSProjectItem; bool flag = false; if (item2 != null) { string customTool = GetCustomTool(item); if ((customTool != null) && (StringComparer.OrdinalIgnoreCase.Compare(customTool, "TextTemplatingFileGenerator") == 0)) { flag = true; } } if (item.ProjectItems != null) { foreach (ProjectItem item3 in item.ProjectItems) { FindProjectItemDependents(item3, toProcess); } } if (flag) { toProcess.Add(item); } }
public override void Execute() { DTE dte = (DTE)GetService(typeof(DTE)); string resourcesFileName = Resources.get_FileNames(1); SourceControlHelper.EnsureWritable(dte, resourcesFileName); ResourcesHelper.AddResource(resourcesFileName, string.Format("{0}{1}", NodeInfo.NodeName, Microsoft.Practices.EnterpriseLibrary.BlockFactory.Properties.Resources.UICommandText), string.Format(Microsoft.Practices.EnterpriseLibrary.BlockFactory.Properties.Resources.RecourceValueNeeded, string.Format("{0}{1}", NodeInfo.NodeName, Microsoft.Practices.EnterpriseLibrary.BlockFactory.Properties.Resources.UICommandText))); ResourcesHelper.AddResource(resourcesFileName, string.Format("{0}{1}", NodeInfo.NodeName, Microsoft.Practices.EnterpriseLibrary.BlockFactory.Properties.Resources.UICommandLongText), string.Format(Microsoft.Practices.EnterpriseLibrary.BlockFactory.Properties.Resources.RecourceValueNeeded, string.Format("{0}{1}", NodeInfo.NodeName, Microsoft.Practices.EnterpriseLibrary.BlockFactory.Properties.Resources.UICommandLongText))); foreach (DesignTimePropertyInfo designTimePropertyInfo in NodeInfo.DesignTimeProperties) { if (!designTimePropertyInfo.Action.Equals(IncludePropertyAction.Ignore)) { string propertyDescriptionResourceEntry = string.Format("{0}{1}", designTimePropertyInfo.PropertyInfo.Name, DescriptionSuffix); ResourcesHelper.AddResource(resourcesFileName, propertyDescriptionResourceEntry, string.Format(Microsoft.Practices.EnterpriseLibrary.BlockFactory.Properties.Resources.RecourceValueNeeded, propertyDescriptionResourceEntry)); } } VSProjectItem vsResources = Resources.Object as VSProjectItem; if (vsResources != null) { vsResources.RunCustomTool(); } }
public void LoadFromTreeNode(TreeNode ns, TreeNode ng, string name, string newname) { foreach (TreeNode node in ns.Nodes) { VSParsers.ProjectItemInfo ps = node.Tag as VSParsers.ProjectItemInfo; VSParsers.ProjectItemInfo bb = new VSParsers.ProjectItemInfo(); bb.vs = ps.vs; bb.ps = ps.ps; VSProjectItem pc = new VSProjectItem(); pc.SubType = ps.psi.SubType; pc.ItemType = ps.psi.ItemType; pc.Include = ps.psi.Include.Replace(name, newname); bb.psi = pc; //if (ps == null) // continue; L.Add(ps); TreeNode nodes = new TreeNode(); nodes.Text = node.Text; nodes.Tag = bb; nodes.Checked = true; nodes.SelectedImageKey = node.SelectedImageKey; nodes.ImageKey = node.ImageKey; ng.Nodes.Add(nodes); LoadFromTreeNode(node, nodes, name, newname); } }
// parameter must be EntityContainer file path public static void GenerateCode(string entityContainerFilepath) { DTE Dte = Package.GetGlobalService(typeof(DTE)) as DTE; DTE2 Dte2 = Package.GetGlobalService(typeof(SDTE)) as DTE2; ThreadHelper.ThrowIfNotOnUIThread(); if (entityContainerFilepath == null) { throw new ArgumentNullException(nameof(entityContainerFilepath)); } if (!entityContainerFilepath.EndsWith(EFModelerFileNameExtension)) { throw new ArgumentOutOfRangeException(nameof(entityContainerFilepath)); } ProjectItem modelProjectItem = Dte2.Solution.FindProjectItem(entityContainerFilepath); // Save file if (Guid.Parse(modelProjectItem.Kind) == VSConstants.GUID_ItemType_PhysicalFile && !modelProjectItem.Saved) { try { modelProjectItem.Save(); } catch (Exception) { throw new Exception($"Save failed for {modelProjectItem.Name}"); } } // TODO - clean up constant string string templateFilename = Path.ChangeExtension(entityContainerFilepath, TextTransformationFileExtension); ProjectItem templateProjectItem = Dte2.Solution.FindProjectItem(templateFilename); VSProjectItem templateVsProjectItem = templateProjectItem?.Object as VSProjectItem; if (templateVsProjectItem == null) { // TODO - place messages in output window or on PCML UI throw new Exception($"Tried to generate code but couldn't find {templateFilename} in the solution."); } try { Dte.StatusBar.Text = $"Generating code from {templateFilename}"; templateVsProjectItem.RunCustomTool(); Dte.StatusBar.Text = $"Finished generating code from {templateFilename}"; } catch (COMException) { string message = $"Encountered an error generating code from {templateFilename}. Please transform T4 template manually."; Dte.StatusBar.Text = message; // TODO - place messages in output window or on PCML UI throw new Exception(message); } }
public void RunCustomTool() { VSProjectItem vsProjectItem = ProjectItem.Object as VSProjectItem; if (vsProjectItem != null) { vsProjectItem.RunCustomTool(); } }
private void ReGenerate(FeatureFileInfo featureFileInfo) { var projectItem = VsxHelper.FindProjectItemByProjectRelativePath(vsProjectScope.Project, featureFileInfo.ProjectRelativePath); if (projectItem != null) { VSProjectItem vsProjectItem = projectItem.Object as VSProjectItem; if (vsProjectItem != null) vsProjectItem.RunCustomTool(); } }
/// <summary> /// Forces the regenerate the SPMetal designer file. /// </summary> /// <param name="owner">The owner.</param> /// <param name="properties">The properties for the SPMetal definition.</param> internal void ForceRegenerate(ISharePointProjectItem owner, SPMetalDefinitionProperties properties) { owner.Annotations.Remove <SPMetalDefinitionProperties>(); owner.Annotations.Add <SPMetalDefinitionProperties>(properties); ProjectItem dteItem = owner.Project.ProjectService.Convert <ISharePointProjectItemFile, ProjectItem>(owner.DefaultFile); VSProjectItem vp = (VSProjectItem)dteItem.Object; vp.RunCustomTool(); }
public VSProjectItem GetVSProjectItem(TreeNode node) { VSParsers.ProjectItemInfo p = node.Tag as VSParsers.ProjectItemInfo; if (p == null) { return(null); } VSProjectItem pp = p.psi; return(pp); }
public void GetItems(TreeNode node, ArrayList L) { VSProjectItem p = GetVSProjectItem(node); L.Add(p); foreach (TreeNode nodes in node.Nodes) { GetItems(nodes, L); } }
private bool RunCustomTool(ProjectItem item, VSProjectItem vsItem, string customTool, OutputWindowHelper outHelper) { bool flag = true; bool flag2 = false; try { string text1 = (string)item.Properties.Item("FullPath").Value; } catch (ArgumentException) { flag = false; outHelper.AddMessage(string.Format(Resources.SkippingNoPath, new object[] { item.Name })); } if ((flag && (item.ProjectItems != null)) && (item.ProjectItems.Count > 0)) { foreach (ProjectItem item2 in item.ProjectItems) { string str = ""; try { str = (string)item2.Properties.Item("FullPath").Value; } catch (ArgumentException) { flag = false; outHelper.AddMessage(string.Format(Resources.SkippingNoPath, new object[] { item2.Name })); } if ((!string.IsNullOrEmpty(str) && !_dte.SourceControl.IsItemUnderSCC(str)) && (File.Exists(str) && ((File.GetAttributes(str) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly))) { flag = false; outHelper.AddMessage(string.Format(Resources.SkippingReadOnly, new object[] { str })); } } } if (flag) { outHelper.AddMessage(string.Format(Resources.RunLine, new object[] { customTool, item.Name })); try { vsItem.RunCustomTool(); outHelper.Add(Resources.LineSucceeded); } catch { outHelper.Add(Resources.LineFailed); flag2 = true; } } return(flag2); }
void OnTransformSelectedExec(object sender, EventArgs e) { this.SaveAllDocumentsBeforeBuild(); _dte.ExecuteCommand("View.Output", ""); OutputWindowHelper outHelper = new OutputWindowHelper(_dte); List <ProjectItem> toProcess = new List <ProjectItem>(); //Get items to be transformed. Project selectedProject = ToDteProject(GetSelectedProject(_serviceProvider)); FindProjectItems(selectedProject, toProcess); outHelper.Clear(); outHelper.AddMessage(string.Format(Resources.StartCodeGen, selectedProject.Name)); outHelper.AddMessage(Resources.Seperator); uint pdwCookie = 0; uint count = (uint)toProcess.Count; IVsStatusbar service = _serviceProvider.GetService(typeof(IVsStatusbar)) as IVsStatusbar; if (service != null) { service.Progress(ref pdwCookie, 1, Resources.TextTemplatingStatusBarLabel, 0, count); } uint complete = 1; bool errorFlag = false; foreach (ProjectItem item in toProcess) { Application.DoEvents(); VSProjectItem vsItem = item.Object as VSProjectItem; if (vsItem != null) { errorFlag |= this.RunCustomTool(item, vsItem, GetCustomTool(item), outHelper); } if (service != null) { service.Progress(ref pdwCookie, 1, Resources.TextTemplatingStatusBarLabel, complete, count); } complete++; Application.DoEvents(); } outHelper.AddMessage(Resources.Seperator); outHelper.AddMessage(Resources.EndCodeGen); if (service != null) { service.Progress(ref pdwCookie, 0, string.Empty, count, count); } }
public ArrayList RenameItems(ArrayList L, string name) { ArrayList N = new ArrayList(); VSParsers.ProjectItemInfo pp = L[0] as VSParsers.ProjectItemInfo; VSProjectItem b = pp.psi; foreach (VSParsers.ProjectItemInfo p in L) { } return(N); }
public ArrayList GetItems(TreeNode node) { ArrayList L = new ArrayList(); VSProjectItem p = GetVSProjectItem(node); L.Add(p); foreach (TreeNode nodes in node.Nodes) { GetItems(nodes, L); } return(L); }
public void DeleteClipboard(TreeNode nodes) { tv.Nodes.Clear(); tv.FullRowSelect = true; tv.CheckBoxes = true; //if (nc == null) // return; //tv.Nodes.Add(nc); List <TreeNode> n = new List <TreeNode>(); n.Add(nodes); LoadTreeNode(n); target = nodes; //src = GetSourceType(nc); dst = GetSourceType(nodes); //if (src == opers.forms) { MessageBox.Show("Remove items has been selected..."); //string prefix = "";/// sourceprefix(nc); ArrayList L = GetItems(nc); VSProjectItem ps = GetVSProjectItem(target); ArrayList T = GetTargetItems(L, dst); VSProject pp = GetVSProject(nodes); pp.RemoveItems(T); //pp.LoadMetaData(L); //pp.SetItems(T, L); //CopyItems(L, T); return; } }
private void watcher_Changed(object sender, FileSystemEventArgs e) { ProjectItem templateProjectItem = this.dte.Solution.FindProjectItem(this.requiredFileNames[1]); if (templateProjectItem != null) { VSProjectItem vsItem = templateProjectItem.Object as VSProjectItem; if (vsItem != null) { vsItem.RunCustomTool(); } } else { this.watching = true; this.TryStopWatching(); } }
public override void Execute() { DTE vs = GetService <DTE>(); string resourcesFileName = Resources.get_FileNames(1); SourceControlHelper.EnsureWritable(vs, resourcesFileName); IDictionaryService dictionaryService = GetService <IDictionaryService>(); ResourcesHelper.AddResource(resourcesFileName, ArgumentsHelper.ReplaceToken(ResourceName, dictionaryService), ArgumentsHelper.ReplaceToken(ResourceValue, dictionaryService)); VSProjectItem vsResources = Resources.Object as VSProjectItem; if (vsResources != null && RunCustomTool) { vsResources.RunCustomTool(); } }
public void CopyItems(ArrayList L, ArrayList T, VSProject vp) { VSProject p = GetVSProject(nc); string folder = p.GetProjectFolder(); int N = L.Count; int i = 0; while (i < N) { VSProjectItem s = L[i] as VSProjectItem; VSProjectItem d = T[i] as VSProjectItem; string source = folder + "\\" + s.Include; string dest = vp.GetProjectFolder() + "\\" + d.Include; if (s.Include == null) { i++; continue; } if (File.Exists(source)) { if (File.Exists(dest) == false) { File.Copy(source, dest); } } else if (Directory.Exists(source)) { if (Directory.Exists(dest) == false) { Directory.CreateDirectory(dest); } } i++; } }
public static void RunT4Template(DTE2 app, string t4TemplateList) { try { string[] t4List = t4TemplateList.Split(new char[] { ',' }); foreach (string t4Template in t4List) { ProjectItem projectItem = app.Solution.FindProjectItem(t4Template.Trim()); if (projectItem == null) { continue; } VSProjectItem vsItem = projectItem.Object as VSProjectItem; vsItem.RunCustomTool(); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } }
public ArrayList GetTargetItems(ArrayList L, string prefix, string target) { ArrayList T = new ArrayList(); foreach (VSProjectItem pp in L) { VSProjectItem p = new VSProjectItem(); p.ItemType = pp.ItemType; p.SubType = pp.SubType; if (pp.Include == null) { p.Include = ""; } if (pp.Include != "") { if (prefix != "") { p.Include = target + pp.Include.Replace(prefix, ""); } else { p.Include = target + "\\" + pp.Include; } } if (p.Include != null) { if (p.Include.StartsWith("\\") == true) { p.Include = p.Include.Remove(0, 1); } } T.Add(p); } return(T); }
internal static void GenerateCode(string filepath = null) { DTE2 dte2 = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SDTE)) as DTE2; string filename = Path.ChangeExtension(filepath ?? dte2.ActiveDocument.FullName, "tt"); VSProjectItem item = dte2.Solution.FindProjectItem(filename)?.Object as VSProjectItem; if (item == null) { Messages.AddError($"Tried to generate code but couldn't find {filename} in the solution."); } else { try { item.RunCustomTool(); } catch (COMException) { Messages.AddError($"Encountered an error generating code from {filename}. Please transform T4 template manually."); } } }
public opers GetSourceType(TreeNode node) { VSProjectItem p = GetVSProjectItem(node); if (p == null) { return(opers.unknown); } if (p.SubType == "Form") { return(opers.forms); } if (p.ItemType == "Forms") { return(opers.forms); } if (p.ItemType == "Folder") { return(opers.folder); } else if (p.ItemType == "Compile") { return(opers.file); } else if (p.ItemType == "File") { return(opers.file); } else if (p.ItemType == "Project") { return(opers.project); } return(opers.unknown); }
private void generateDataset(string datasetFilename, string datasetClassName) { if (datasetFilename == null || datasetFilename == "") { throw new Exception("No schema filename specified"); } if (this.checkedListBoxAdapters.CheckedItems.Count == 0) { throw new Exception("No data adapter items selected."); } int extensionStart = datasetFilename.LastIndexOf('.'); if (extensionStart == -1) { throw new Exception("Invalid data set filename " + extensionStart); } string datasetName = datasetFilename.Substring(0, extensionStart); VirtuosoDataAdapter adapter; DataSet targetDataSet = new DataSet(); DataSet sourceDataSet; for (int index = 0; index < checkedListBoxAdapters.CheckedItems.Count; index++) { adapter = null; foreach (IComponent c in _host.Container.Components) { if (c is VirtuosoDataAdapter && c.ToString() == this.checkedListBoxAdapters.CheckedItems[index].ToString()) { adapter = (VirtuosoDataAdapter)c; break; } } if (adapter == null) { throw new Exception("Inconsistency, failed to locate data adapter"); } sourceDataSet = new DataSet(); try { adapter.MissingSchemaAction = MissingSchemaAction.Add; if (adapter.MissingMappingAction == MissingMappingAction.Error) { adapter.MissingMappingAction = MissingMappingAction.Ignore; } DataTable [] tables = adapter.FillSchema(sourceDataSet, SchemaType.Mapped); // // Set all string columns to length -1 so that the xml schema file // generates correctly // foreach (DataTable table in tables) { foreach (DataColumn column in table.Columns) { if (column.DataType == typeof(string)) { column.MaxLength = -1; } } } // // Merge data table into main data set // foreach (DataTable table in tables) { if (!targetDataSet.Tables.Contains(table.TableName)) { targetDataSet.Merge(table); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } // // Locate project items collection where .xsd file should be added // if (_projectItem == null || _projectItem.Collection == null) { throw new ApplicationException("No project information available. Unable to generate data set file."); } object parent = _projectItem.Collection.Parent; ProjectItems projectItems = null; while (parent != null) { if ((parent as Project) != null) { // // The parent was the project node! // projectItems = ((Project)parent).ProjectItems; break; } if ((parent as ProjectItem) == null) { // // Parent node was not a project and not a project item... // break; } if (string.Compare(((ProjectItem)parent).Kind, EnvDTE.Constants.vsProjectItemKindPhysicalFolder, true, System.Globalization.CultureInfo.InvariantCulture) != 0) { // // Add .xsd file to folder // projectItems = ((ProjectItem)parent).ProjectItems; break; } parent = ((ProjectItem)parent).Collection.Parent; } Type xsdType = null; if (datasetClassName != null) { xsdType = _host.GetType(datasetClassName); } // // Now merge the existing data set into the target // if (datasetClassName != null && xsdType != null) { ConstructorInfo constructor = xsdType.GetConstructor(new Type[] {}); if (constructor != null) { sourceDataSet = (DataSet)constructor.Invoke(null); if (sourceDataSet != null) { foreach (DataTable table in sourceDataSet.Tables) { if (!targetDataSet.Tables.Contains(table.TableName)) { targetDataSet.Merge(table); } } } } } // // Calculate filename for dataset XML schema file // if (_projectItem.Properties == null) { throw new ApplicationException("Unable to locate project item properties."); } if (_projectItem.Properties.Item("FullPath") == null) { throw new ApplicationException("Unable to resolve full path of the dataset file."); } string xsdFilename = Path.Combine(Path.GetDirectoryName( (string)_projectItem.Properties.Item("FullPath").Value), datasetFilename); ProjectItem xsdItem = projectItems.DTE.Solution.FindProjectItem(xsdFilename); if (datasetClassName == null) { if (xsdItem != null || File.Exists(xsdFilename)) { if (MessageBox.Show(this, "File " + xsdFilename + " already exists. Overwrite?", "Overwrite Schema File", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) { DialogResult = DialogResult.None; return; } } } targetDataSet.Namespace = "http://www.tempuri.org/" + datasetName + ".xsd"; targetDataSet.DataSetName = datasetName; targetDataSet.WriteXmlSchema(xsdFilename); // // Add the .xsd file to the project, unless it already existed // if (xsdItem == null) { xsdItem = projectItems.AddFromFileCopy(xsdFilename); } // // Set the CustomTool property to "MSDataSetGenerator" // if (xsdItem != null && xsdItem.Properties != null) { Property custToolsProp = xsdItem.Properties.Item("CustomTool"); if (custToolsProp != null) { if (custToolsProp.Value.Equals(string.Empty)) { custToolsProp.Value = "MSDataSetGenerator"; } } else { VSProjectItem vsProjectItem = (VSProjectItem)xsdItem.Object; vsProjectItem.RunCustomTool(); } } // // Add a component to the designer if none exists // foreach (IComponent c in _host.Container.Components) { if (c is DataSet) { if (String.Compare(((DataSet)c).DataSetName, datasetName, true) == 0) { // // Found one, done! // return; } } } if (xsdType == null) { // // Figure out the fully qualified namespace name // Property namespaceProp = null; if ((parent as Project) != null) { namespaceProp = ((Project)parent).Properties.Item("RootNamespace"); } else if ((parent as ProjectItem) != null) { namespaceProp = ((ProjectItem)parent).Properties.Item("DefaultNamespace"); } if (namespaceProp != null) { xsdType = _host.GetType(namespaceProp.Value + "." + datasetName); } } // // Add the component to the designer // if (xsdType != null) { if (_host.Container.Components[datasetName] == null) { _host.CreateComponent(xsdType, datasetName); } else { _host.CreateComponent(xsdType); } } }
private bool RunCustomTool(ProjectItem item, VSProjectItem vsItem, string customTool, OutputWindowHelper outHelper) { bool flag = true; bool flag2 = false; try { string text1 = (string)item.Properties.Item("FullPath").Value; } catch (ArgumentException) { flag = false; outHelper.AddMessage(string.Format(Resources.SkippingNoPath, new object[] { item.Name })); } if ((flag && (item.ProjectItems != null)) && (item.ProjectItems.Count > 0)) { foreach (ProjectItem item2 in item.ProjectItems) { string str = ""; try { str = (string)item2.Properties.Item("FullPath").Value; } catch (ArgumentException) { flag = false; outHelper.AddMessage(string.Format(Resources.SkippingNoPath, new object[] { item2.Name })); } if ((!string.IsNullOrEmpty(str) && !_dte.SourceControl.IsItemUnderSCC(str)) && (File.Exists(str) && ((File.GetAttributes(str) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly))) { flag = false; outHelper.AddMessage(string.Format(Resources.SkippingReadOnly, new object[] { str })); } } } if (flag) { outHelper.AddMessage(string.Format(Resources.RunLine, new object[] { customTool, item.Name })); try { vsItem.RunCustomTool(); outHelper.Add(Resources.LineSucceeded); } catch { outHelper.Add(Resources.LineFailed); flag2 = true; } } return flag2; }
public void ReloadClipboard(TreeNode nodes) { tv.Nodes.Clear(); tv.FullRowSelect = true; tv.CheckBoxes = true; if (nc == null) { return; } tv.Nodes.Add(nc); target = nodes; src = GetSourceType(nc); dst = GetSourceType(nodes); if (src == opers.forms) { MessageBox.Show("The copy of form has been selected..."); string prefix = sourceprefix(nc); ArrayList L = GetItems(nc); VSProjectItem ps = GetVSProjectItem(target); VSProject pp = GetVSProject(nodes); ArrayList T = GetTargetItems(L, prefix, ps.Include); pp.LoadMetaData(L); pp.SetItems(T, L); CopyItems(L, T, pp); return; } if (src == opers.folder) { if (dst == opers.folder) { MessageBox.Show("Two folders have been selected..."); //return; string prefix = sourceprefix(nc); ArrayList L = GetItems(nc); VSProjectItem ps = GetVSProjectItem(target); ArrayList T = GetTargetItems(L, prefix, ps.Include); VSProject pp = GetVSProject(nodes); pp.LoadMetaData(L); pp.SetItems(T, L); CopyItems(L, T, pp); return; } if (dst == opers.project) { MessageBox.Show("The copy to project has been selected..."); //return; string prefix = sourceprefix(nc); ArrayList L = GetItems(nc); VSProjectItem ps = GetVSProjectItem(target); ArrayList T = GetTargetItems(L, prefix, ps.Include); VSProject pp = GetVSProject(nodes); pp.LoadMetaData(L); pp.SetItems(T, L); CopyItems(L, T); return; } } if (src == opers.file) { if (dst == opers.folder) { string prefix = sourceprefix(nc); ArrayList L = GetItems(nc); VSProjectItem ps = GetVSProjectItem(target); ArrayList T = GetTargetItems(L, prefix, ps.Include); VSProject pp = GetVSProject(nodes); pp.LoadMetaData(L); pp.SetItems(T, L); CopyItems(L, T); return; } if (dst == opers.project) { MessageBox.Show("The copy of the file to project has been selected..."); //return; string prefix = sourceprefix(nc); ArrayList L = GetItems(nc); VSProjectItem ps = GetVSProjectItem(target); if (ps.Include == null) { ps.Include = ""; } ArrayList T = GetTargetItems(L, prefix, ps.Include); VSProject pp = GetVSProject(nodes); pp.LoadMetaData(L); pp.SetItems(T, L); CopyItems(L, T); return; } } }
/// <summary> /// Generate a code file for the current xml file contents. Loads /// settings for the file off the Plix.xml settings file in the project to /// get the generation transform and other settings to apply to the specific file. /// </summary> /// <param name="fileContents">Contents of an xml file to transform</param> /// <param name="defaultNamespace">The namespace provided in the property grid</param> /// <returns>Contents of the corresponding code file</returns> private string GenerateCode(string fileContents, string defaultNamespace) { #if VerifyUIThread Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); #endif // Make sure we have a CodeDomProvider CodeDomProvider provider = CodeDomProvider; if (provider == null) { return(string.Empty); } // Get the current project item and project information EnvDTE.ProjectItem projectItem = CurrentProjectItem; string sourceFile = (string)projectItem.Properties.Item("LocalPath").Value; EnvDTE.Project project = projectItem.ContainingProject; string projectFile = (string)project.Properties.Item("LocalPath").Value; string projectLocation = projectFile.Substring(0, projectFile.LastIndexOf('\\') + 1); // If this is the Plix.xml settings file, then regenerate all other mentioned NUPlixLoader files if (0 == string.Compare(projectItem.Name, PlixProjectSettingsFile, true, CultureInfo.InvariantCulture)) { RunCustomTool( project.ProjectItems, projectItem, delegate(EnvDTE.ProjectItem matchItem) { #if VerifyUIThread Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); #endif VSProjectItem vsProjItem = matchItem.Object as VSProjectItem; if (vsProjItem != null) { vsProjItem.RunCustomTool(); } }); StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement( @"Empty file generated by NUPlixLoader for Plix.xml. Setting NUPlixLoader as the custom tool on the Plix.xml settings file enables automatic regeneration of other NUPlixLoader files in the project when the settings file is changed. There is no way to both successfully trigger regeneration and avoid writing this file."), writer, null); return(writer.ToString()); } // Load a language formatter for this file extension string fileExtension = CodeDomProvider.FileExtension; if (fileExtension.StartsWith(".")) { fileExtension = fileExtension.Substring(1); } XslCompiledTransform formatter = FormatterManager.GetFormatterTransform(fileExtension); if (formatter == null) { StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "A PLiX formatter transform for the '{0}' language was not found.", fileExtension)), writer, null); return(writer.ToString()); } // Get options for this xml file XsltArgumentList arguments = new XsltArgumentList(); string automationObjectName; string transformFile = LoadProjectSettings(sourceFile, projectLocation, arguments, project, out automationObjectName); // MSBUG: Beta2 There's a nasty bug with single-file generators right now where // the text for an open file that is not in a text document is // passed through as encoded bytes in the string. EnvDTE.Document itemDocument = projectItem.Document; if (itemDocument != null && "XML" != itemDocument.Language) { if (fileContents.Length > 1) { char[] leadChars = fileContents.ToCharArray(0, 2); byte[] leadBytes = new byte[2 * sizeof(char)]; GCHandle handle = GCHandle.Alloc(leadBytes, GCHandleType.Pinned); Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), 2); handle.Free(); EncodingInfo[] encodingInfos = Encoding.GetEncodings(); int encodingsCount = encodingInfos.Length; for (int i = 0; i < encodingsCount; ++i) { EncodingInfo encodingInfo = encodingInfos[i]; Encoding encoding = encodingInfo.GetEncoding(); byte[] preamble = encoding.GetPreamble(); int preambleByteCount = preamble.Length; if (preambleByteCount != 0) { Debug.Assert(preambleByteCount <= 4); int j; for (j = 0; j < preambleByteCount; ++j) { if (preamble[j] != leadBytes[j]) { break; } } if (j == preambleByteCount) { Decoder decoder = encoding.GetDecoder(); leadChars = fileContents.ToCharArray(); int startCharCount = leadChars.Length; leadBytes = new byte[startCharCount * sizeof(char)]; int byteCount = leadBytes.Length - preambleByteCount; GCHandle handle2 = GCHandle.Alloc(leadBytes, GCHandleType.Pinned); Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), startCharCount); handle2.Free(); int finalCharCount = decoder.GetCharCount(leadBytes, preambleByteCount, byteCount, true); char[] finalChars = new char[finalCharCount + 1]; decoder.GetChars(leadBytes, preambleByteCount, byteCount, finalChars, 0, true); // Hack within a hack to make sure that the Xml element has a trailing >, // byte data in a string has a tendency to lose the last byte char testChar = finalChars[finalCharCount - 1];; if (testChar != '>' && !char.IsWhiteSpace(testChar)) { finalChars[finalCharCount] = '>'; ++finalCharCount; } fileContents = new string(finalChars, 0, finalCharCount); } } } } } // Resolve any file redirections here. File redirection allows the same source file // to generate multiple outputs via multiple transforms. string alternateSourceFile = null; using (StringReader stringReader = new StringReader(fileContents)) { try { using (XmlTextReader reader = new XmlTextReader(stringReader)) { if (XmlNodeType.Element == reader.MoveToContent()) { if (reader.NamespaceURI == RedirectNamespace && reader.LocalName == RedirectElementName) { string relativeTargetSourceFile = reader.GetAttribute(RedirectTargetAttribute); FileInfo targetSourceFileInfo = new FileInfo(sourceFile.Substring(0, sourceFile.LastIndexOf('\\') + 1) + relativeTargetSourceFile); if (targetSourceFileInfo.Exists) { alternateSourceFile = targetSourceFileInfo.FullName; sourceFile = alternateSourceFile; try { itemDocument = null; itemDocument = project.DTE.Documents.Item(alternateSourceFile); } catch (ArgumentException) { // Swallow if the document is not open } } else { StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "Redirection target file '{0}' not found", relativeTargetSourceFile)), writer, null); return(writer.ToString()); } } } } } catch (XmlException ex) { return(GenerateExceptionInformation(ex, provider)); } } // Add standard defined attributes to the argument list string projectNamespace = (string)project.Properties.Item("DefaultNamespace").Value; if (null == arguments.GetParam("ProjectPath", "")) { arguments.AddParam("ProjectPath", "", projectLocation); } if (null == arguments.GetParam("SourceFile", "")) { arguments.AddParam("SourceFile", "", sourceFile.Substring(projectLocation.Length)); } if (null == arguments.GetParam("CustomToolNamespace", "")) { if (defaultNamespace == null || defaultNamespace.Length == 0) { defaultNamespace = projectNamespace; } arguments.AddParam("CustomToolNamespace", "", defaultNamespace); } if (null == arguments.GetParam("ProjectNamespace", "")) { arguments.AddParam("ProjectNamespace", "", projectNamespace); } try { XslCompiledTransform transform = null; if (transformFile != null) { transform = new XslCompiledTransform(); using (FileStream transformStream = new FileStream(transformFile, FileMode.Open, FileAccess.Read)) { using (StreamReader reader = new StreamReader(transformStream)) { transform.Load(new XmlTextReader(reader), XsltSettings.TrustedXslt, XmlUtility.CreateFileResolver(transformFile)); } } } MemoryStream plixStream = (transform != null) ? new MemoryStream() : null; using (XmlWriter xmlTextWriter = (transform != null) ? XmlWriter.Create(plixStream, transform.OutputSettings) : null) { // Variables that need to be disposed TextReader reader = null; Stream docStream = null; try { // First try to get data from the live object string docText = null; if (itemDocument != null) { if (automationObjectName != null) { docStream = itemDocument.Object(automationObjectName) as Stream; if (docStream != null) { reader = new StreamReader(docStream); } } // Fall back on getting the contents of the text buffer from the live document if (reader == null) { EnvDTE.TextDocument textDoc = itemDocument.Object("TextDocument") as EnvDTE.TextDocument; if (textDoc != null) { docText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint); reader = new StringReader(docText); } } } // If this is a redirection, then pull direction from the file if (reader == null && alternateSourceFile != null) { reader = new StreamReader(alternateSourceFile); } // Fallback on the default reading mechanism if (reader == null) { docText = fileContents; reader = new StringReader(fileContents); } if (transform == null) { XmlReaderSettings testPlixDocumentReaderSettings = new XmlReaderSettings(); testPlixDocumentReaderSettings.CloseInput = false; bool plixDocument = false; try { using (XmlReader testPlixDocumentReader = XmlReader.Create(reader, testPlixDocumentReaderSettings)) { testPlixDocumentReader.MoveToContent(); if (testPlixDocumentReader.NodeType == XmlNodeType.Element && testPlixDocumentReader.NamespaceURI == PlixSchemaNamespace) { plixDocument = true; } } } catch (XmlException ex) { return(GenerateExceptionInformation(ex, provider)); } if (!plixDocument) { StringWriter writer = new StringWriter(); provider.GenerateCodeFromStatement(new CodeCommentStatement("Transform file not found"), writer, null); GenerateNUPlixLoaderExceptionLine(writer, provider); return(writer.ToString()); } if (docText != null) { reader.Dispose(); reader = new StringReader(docText); } else { StreamReader streamReader = (StreamReader)reader; streamReader.BaseStream.Position = 0; } } else { // Use an XmlTextReader here instead of an XPathDocument // so that our transforms support the xsl:preserve-space element transform.Transform(new XmlTextReader(reader), arguments, xmlTextWriter, XmlUtility.CreateFileResolver(sourceFile)); plixStream.Position = 0; } // From the plix stream, generate the code using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { using (XmlReader plixReader = (plixStream != null) ? XmlReader.Create(plixStream, PlixReaderSettings) : XmlReader.Create(reader, PlixReaderSettings)) { formatter.Transform(plixReader, new XsltArgumentList(), writer); } return(writer.ToString()); } } finally { if (reader != null) { (reader as IDisposable).Dispose(); } if (docStream != null) { (docStream as IDisposable).Dispose(); } } } } catch (Exception ex) { return(GenerateExceptionInformation(ex, provider)); } finally { // Regardless of how we finish process this file, we need to find files redirected to this // one and regenerate them. if (alternateSourceFile == null) // We only redirect one level { FileInfo sourceFileInfo = new FileInfo(sourceFile); RunCustomTool( project.ProjectItems, projectItem, delegate(EnvDTE.ProjectItem matchItem) { #if VerifyUIThread Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); #endif VSProjectItem vsProjItem = matchItem.Object as VSProjectItem; if (vsProjItem != null) { string itemFile = (string)matchItem.Properties.Item("LocalPath").Value; EnvDTE.Document liveDoc; EnvDTE.TextDocument textDoc; string liveText = null; if (null != (liveDoc = matchItem.Document) && null != (textDoc = liveDoc.Object("TextDocument") as EnvDTE.TextDocument)) { liveText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint); } try { using (FileStream fileStream = (liveText == null) ? new FileStream(itemFile, FileMode.Open, FileAccess.Read) : null) { using (XmlTextReader reader = new XmlTextReader((liveText == null) ? new StreamReader(fileStream) as TextReader : new StringReader(liveText))) { if (XmlNodeType.Element == reader.MoveToContent()) { if (reader.NamespaceURI == RedirectNamespace && reader.LocalName == RedirectElementName) { FileInfo targetSourceFileInfo = new FileInfo(itemFile.Substring(0, itemFile.LastIndexOf('\\') + 1) + reader.GetAttribute(RedirectTargetAttribute)); if (0 == string.Compare(sourceFileInfo.FullName, targetSourceFileInfo.FullName, true, CultureInfo.CurrentCulture)) { vsProjItem.RunCustomTool(); } } } } } } catch (XmlException) { // Swallow anything that Xml gripes about } } }); } } }
public void RenameVSProjectItems() { string name = textBox1.Text; ncc = new TreeNode(); ncc.Text = name; if (project_node != null) { project_node.Text = name; } VSParsers.ProjectItemInfo p = nc.Tag as VSParsers.ProjectItemInfo; //VSParsers.ProjectItemInfo psp = new VSParsers.ProjectItemInfo(); if (p.psi != null) { if (p.psi.ItemType == "Folder") { RenameFolder(); return; } } VSProjectItem ppp = null; if (p != null) { ppp = p.psi; } VSParsers.ProjectItemInfo bbb = new VSParsers.ProjectItemInfo(); bbb.vs = p.vs; bbb.ps = p.ps; VSProjectItem pcp = new VSProjectItem(); pcp.SubType = p.psi.SubType; pcp.ItemType = p.psi.ItemType; bbb.psi = pcp; ncc.Tag = bbb; if (p == null) { return; } if (p.psi == null) { return; } string names = p.psi.Include; //string[] cc = names.Split("\\".ToCharArray()); string master;// = GetString(cc); // master = cc[cc.Length - 2]; VSParsers.ProjectItemInfo psp = nc.Tag as VSParsers.ProjectItemInfo; string newname = name; string incc = p.psi.Include; if (psp.psi.Name != null) { master = GetName(psp.psi.Name); newname = name; pcp.Include = incc; incc = incc.Replace(master, newname); pcp.Include = incc; if (vp != null) { vp.RenameItem(pcp.ItemType, psp.psi.Include, pcp.Include); } } else { master = GetName(nc.Text); } foreach (TreeNode node in nc.Nodes) { VSParsers.ProjectItemInfo ps = node.Tag as VSParsers.ProjectItemInfo; VSProjectItem pp = null; if (ps != null) { pp = ps.psi; } VSParsers.ProjectItemInfo bb = new VSParsers.ProjectItemInfo(); bb.vs = ps.vs; bb.ps = ps.ps; VSProjectItem pc = new VSProjectItem(); pc.SubType = ps.psi.SubType; pc.ItemType = ps.psi.ItemType; if (ps.psi.ItemType == null) { pc.ItemType = ps.psi.SubType; } bb.psi = pc; string inc = ps.psi.Include; //string names = p.psi.Include; string[] d = inc.Split("\\.".ToCharArray()); //master = inc;// GetString(d); //if(d.Length > 1) //d[d.Length - 2] = name; //newname = GetString(d); newname = name; inc = inc.Replace(master, newname); pc.Include = inc; if (vp != null) { vp.RenameItem(pc.ItemType, ps.psi.Include, pc.Include, master, newname); } node.Text = inc; TreeNode nodes = new TreeNode(); nodes.Text = node.Text; nodes.SelectedImageKey = node.SelectedImageKey; nodes.ImageKey = node.ImageKey; nodes.Checked = true; ncc.Nodes.Add(nodes); if (ps != null) { if (bb != null) { pc.Include = inc; nodes.Tag = bb; } } LoadFromTreeNode(node, nodes, master, newname); } LoadTreeNodes(ncc); }
public void RenameFolder() { string name = textBox1.Text; tv.BeginUpdate(); ncc = new TreeNode(); ncc.Text = name; ncc.SelectedImageKey = nc.SelectedImageKey; ncc.ImageKey = nc.ImageKey; VSParsers.ProjectItemInfo p = nc.Tag as VSParsers.ProjectItemInfo; string folder = p.psi.Include; string newfolder = ""; string[] dd = folder.Split("\\".ToCharArray()); if (dd.Length > 0) { dd[dd.Length - 1] = name; newfolder = ""; int a = 0; foreach (string g in dd) { if (a != 0) { newfolder += "\\"; } newfolder += g; a++; } } vp.FolderCreate(newfolder); string newname = newfolder + "\\"; string newnames = newfolder; string master = folder + "\\"; string masters = folder + "\\"; foreach (TreeNode node in nc.Nodes) { VSParsers.ProjectItemInfo ps = node.Tag as VSParsers.ProjectItemInfo; VSProjectItem pp = null; if (ps != null) { pp = ps.psi; } VSParsers.ProjectItemInfo bb = new VSParsers.ProjectItemInfo(); bb.vs = ps.vs; bb.ps = ps.ps; VSProjectItem pc = new VSProjectItem(); pc.SubType = ps.psi.SubType; pc.ItemType = ps.psi.ItemType; if (ps.psi.ItemType == null) { pc.ItemType = ps.psi.SubType; } bb.psi = pc; string inc = ps.psi.Include; //string[] d = inc.Split("\\.".ToCharArray()); inc = inc.Replace(master, newname); pc.Include = inc; if (vp != null) { vp.RenameItem(pc.ItemType, ps.psi.Include, pc.Include, master, newname); } node.Text = inc; TreeNode nodes = new TreeNode(); nodes.Text = node.Text.Replace(newname, ""); nodes.SelectedImageKey = node.SelectedImageKey; nodes.ImageKey = node.ImageKey; nodes.Checked = true; ncc.Nodes.Add(nodes); if (ps != null) { if (bb != null) { pc.Include = inc; nodes.Tag = bb; } } //LoadFromTreeNode(node, nodes, master, newname); if (node.Nodes.Count > 0) { RenameSubFolders(node, master, newname, nodes); } } //LoadFromTreeNode(node, nodes, master, newname); LoadTreeNodes(ncc); tv.EndUpdate(); }
public void RenameSubFolders(TreeNode nc, string master, string newname, TreeNode ng) { foreach (TreeNode node in nc.Nodes) { VSParsers.ProjectItemInfo ps = node.Tag as VSParsers.ProjectItemInfo; VSProjectItem pp = null; if (ps != null) { pp = ps.psi; } VSParsers.ProjectItemInfo bb = new VSParsers.ProjectItemInfo(); bb.vs = ps.vs; bb.ps = ps.ps; VSProjectItem pc = new VSProjectItem(); pc.SubType = ps.psi.SubType; pc.ItemType = ps.psi.ItemType; if (ps.psi.ItemType == null) { pc.ItemType = ps.psi.SubType; } bb.psi = pc; string inc = ps.psi.Include; //string[] d = inc.Split("\\.".ToCharArray()); inc = inc.Replace(master, newname); pc.Include = inc; if (vp != null) { vp.RenameItem(pc.ItemType, ps.psi.Include, pc.Include, master, newname); } node.Text = inc; TreeNode nodes = new TreeNode(); //nodes.Text = node.Text; nodes.Text = node.Text.Replace(newname, ""); nodes.SelectedImageKey = node.SelectedImageKey; nodes.ImageKey = node.ImageKey; nodes.Checked = true; ng.Nodes.Add(nodes); if (ps != null) { if (bb != null) { pc.Include = inc; nodes.Tag = bb; } } // LoadFromTreeNode(node, nodes, master, newname); if (node.Nodes.Count > 0) { RenameSubFolders(node, master, newname, nodes); } } }
private bool RunCustomTool(ProjectItem item) { string customTool = GetCustomTool(item); VSProjectItem item2 = item.Object as VSProjectItem; VSWebProjectItem2 item3 = item.Object as VSWebProjectItem2; bool flag = true; bool flag2 = false; try { string text1 = (string)item.Properties.Item("FullPath").Value; } catch (ArgumentException) { flag = false; this.WriteLine(Microsoft.VisualStudio.TextTemplating.VSHost.Resources.OrchestrationSkippingNoPath, new object[] { item.Name }); } if ((flag && (item.ProjectItems != null)) && (item.ProjectItems.Count > 0)) { foreach (ProjectItem item4 in item.ProjectItems) { string str2 = ""; try { str2 = (string)item4.Properties.Item("FullPath").Value; } catch (ArgumentException) { flag = false; this.WriteLine(Microsoft.VisualStudio.TextTemplating.VSHost.Resources.OrchestrationSkippingNoPath, new object[] { item4.Name }); } if ((!string.IsNullOrEmpty(str2) && !this.Dte.SourceControl.IsItemUnderSCC(str2)) && (File.Exists(str2) && ((File.GetAttributes(str2) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly))) { flag = false; this.WriteLine(Microsoft.VisualStudio.TextTemplating.VSHost.Resources.OrchestrationSkippingReadOnly, new object[] { str2 }); } } } if (flag) { this.Write(Microsoft.VisualStudio.TextTemplating.VSHost.Resources.OrchestratorRunLine, new object[] { customTool, item.Name }); try { this.ClearCustomTextTemplatingToolErrorStatus(); if (item2 != null) { item2.RunCustomTool(); } else if (item3 != null) { item3.RunCustomTool(); } flag2 = this.FindCustomTextTemplatingToolErrorStatus(); if (flag2) { this.WriteLine(Microsoft.VisualStudio.TextTemplating.VSHost.Resources.OrchestrationLineFailed); } else { this.WriteLine(Microsoft.VisualStudio.TextTemplating.VSHost.Resources.OrchestrationLineSucceeded); } } catch (Exception exception) { if (CriticalException.IsCriticalException(exception)) { throw; } this.WriteLine(Microsoft.VisualStudio.TextTemplating.VSHost.Resources.OrchestrationLineFailed); flag2 = true; } } this.outputPane.Activate(); return(flag2); }