/// <summary> /// Adds item to owner. /// Before it calls <see cref="IGStripManagerCallbacks.ItemAdding"/>. /// </summary> /// <param name="x">item's element. This function assigns item to its annotation. Caller must assign x to item.Tag before calling this function.</param> /// <param name="item">Can be ToolStripMenuItem, ToolStripButton, ToolStripSplitButton, ToolStripDropDownButton, ToolStripSpringTextBox, ToolStripSpringComboBox, ToolStripSeparator.</param> /// <param name="owner">ToolStrip, MenuStrip or ToolStripDropDownMenu to which to add this item.</param> /// <param name="insertAt">If not negative, inserts at this index. If negative, adds to the end.</param> void _AddChildItem(XElement x, ToolStripItem item, ToolStrip owner, int insertAt = -1) { if (owner != MenuBar) { item.MouseUp += _OnMouseUp; //context menu if (!(owner is ToolStripDropDownMenu)) { item.MouseDown += _OnMouseDown; //Alt+drag } } Debug.Assert(x != null && object.ReferenceEquals(x, item.Tag)); x.AddAnnotation(item); //info: this method is optimized, it just assigns item to its member 'object annotation;'. Creates array only if assigned more items. _callbacks.ItemAdding(item, owner); var k = owner.Items; if (insertAt >= 0) { k.Insert(insertAt, item); } else { k.Add(item); } //if(item is ToolStripMenuItem mi) AOutput.Write(mi.HasDropDown, mi.Tag); }
LiveElement() { var xElement = new XElement("Unknown"); xElement.AddAnnotation(this); _element = new BehaviorSubject <XElement>(xElement); }
// Get the latest transaction in the depot that occurred the last time wspace was successfully updated, // otherwise returns null on error. Adds wspace to the transaction as an annotation. AcUtilsException // caught and logged in %LOCALAPPDATA%\AcTools\Logs\WSpaceTransLevel-YYYY-MM-DD.log on hist command failure. // Exception caught and logged in same for a range of exceptions. private static async Task <XElement> latestTransAsync(AcWorkspace wspace) { XElement trans = null; // assume failure try { AcResult r = await AcCommand.runAsync($@"hist -fx -p ""{wspace.Depot}"" -t {wspace.UpdateLevel}"); if (r != null && r.RetVal == 0) { XElement xml = XElement.Parse(r.CmdResult); trans = xml.Element("transaction"); if (trans != null) { trans.AddAnnotation(wspace); } } } catch (AcUtilsException ecx) { AcDebug.Log($"AcUtilsException caught and logged in Program.latestTransAsync{Environment.NewLine}{ecx.Message}"); } catch (Exception ecx) { AcDebug.Log($"Exception caught and logged in Program.latestTransAsync{Environment.NewLine}{ecx.Message}"); } return(trans); }
public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) { var record = (PropertyTypeReferenceRecord)((BamlRecordNode)node).Record; var attr = ctx.ResolveProperty(record.AttributeId); var type = ctx.ResolveType(record.TypeId); var typeName = ctx.ToString(parent.Xaml, type); var elem = new BamlElement(node); var elemAttr = ctx.ResolveProperty(record.AttributeId); elem.Xaml = new XElement(elemAttr.ToXName(ctx, null)); elem.Xaml.Element.AddAnnotation(elemAttr); parent.Xaml.Element.Add(elem.Xaml.Element); var typeElem = new XElement(ctx.GetXamlNsName("TypeExtension", parent.Xaml)); typeElem.AddAnnotation(ctx.ResolveType(0xfd4d)); // Known type - TypeExtension typeElem.Add(new XElement(ctx.GetPseudoName("Ctor"), typeName)); elem.Xaml.Element.Add(typeElem); elemAttr.DeclaringType.ResolveNamespace(elem.Xaml, ctx); elem.Xaml.Element.Name = elemAttr.ToXName(ctx, null); return(elem); }
public static T ToXTypedElement <T>(XElement xe) where T : XTypedElement, new() { T t; if (xe != null) { T xoSubType = XTypedServices.GetAnnotation <T>(xe); if (xoSubType == null) { xoSubType = Activator.CreateInstance <T>(); if (!XTypedServices.TypeValid(xoSubType, xe.Name)) { throw new LinqToXsdException(string.Concat("Element is not an instance of type ", xoSubType.GetType())); } xoSubType.Untyped = xe; xe.AddAnnotation(new XTypedElementAnnotation(xoSubType)); } t = xoSubType; } else { t = default(T); } return(t); }
public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) { var record = (PropertyTypeReferenceRecord)((BamlRecordNode)node).Record; var attr = ctx.ResolveProperty(record.AttributeId); var type = ctx.ResolveType(record.TypeId); var typeName = ctx.ToString(parent.Xaml, type); var elem = new BamlElement(node); var elemAttr = ctx.ResolveProperty(record.AttributeId); elem.Xaml = new XElement(elemAttr.ToXName(ctx, null)); if (attr.ResolvedMember.FullNameIs("System.Windows.Style", "TargetType")) { parent.Xaml.Element.AddAnnotation(new TargetTypeAnnotation(type)); } elem.Xaml.Element.AddAnnotation(elemAttr); parent.Xaml.Element.Add(elem.Xaml.Element); var typeElem = new XElement(ctx.GetKnownNamespace("TypeExtension", XamlContext.KnownNamespace_Xaml, parent.Xaml)); typeElem.AddAnnotation(ctx.ResolveType(0xfd4d)); // Known type - TypeExtension typeElem.Add(new XElement(ctx.GetPseudoName("Ctor"), typeName)); elem.Xaml.Element.Add(typeElem); elemAttr.DeclaringType.ResolveNamespace(elem.Xaml, ctx); elem.Xaml.Element.Name = elemAttr.ToXName(ctx, null); return(elem); }
//Cast XElement to XTypedElement type T, Called from Load and Parse public static T ToXTypedElement <T>(XElement xe) where T : XTypedElement { if (xe == null) { return(null); } T xoSubType = GetAnnotation <T>(xe); if (xoSubType == null) { //No association bet XTypedElement and xelement xoSubType = (T)Activator.CreateInstance(typeof(T), nonPublic: true); if (TypeValid(xoSubType, xe.Name)) { xoSubType.Untyped = xe; xe.AddAnnotation(new XTypedElementAnnotation(xoSubType)); } else { throw new LinqToXsdException("Element is not an instance of type " + xoSubType.GetType()); } } return(xoSubType); }
// Returns the attributes for the element in stream if the query succeeded, otherwise null. // AcUtilsException caught and logged in %LOCALAPPDATA%\AcTools\Logs\EvilTwins-YYYY-MM-DD.log on stat command failure. // Exception caught and logged in same for a range of exceptions. private static async Task <XElement> getElementInfoAsync(AcStream stream, string element) { XElement e = null; try { AcResult r = await AcCommand.runAsync($@"stat -fx -s ""{stream}"" ""{element}"""); if (r != null && r.RetVal == 0) { XElement xml = XElement.Parse(r.CmdResult); e = xml.Element("element"); e.AddAnnotation(stream); // add stream since it's not in the XML } } catch (AcUtilsException ecx) { AcDebug.Log($"AcUtilsException caught and logged in Program.getElementInfoAsync{Environment.NewLine}{ecx.Message}"); } catch (Exception ecx) { AcDebug.Log($"Exception caught and logged in Program.getElementInfoAsync{Environment.NewLine}{ecx.Message}"); } return(e); }
private void ProcessRootNodes(XElement result) { //restore auto states from breaks foreach (var p in result.Elements("p")) { var a = p.Attribute("__auto"); if (null != a) { a.Remove(); p.AddAnnotation(AutoPara.Default); } } foreach (var n in result.Nodes().ToArray()) { if (null != n as XElement && (n as XElement).Name.LocalName == "p") { continue; } if (null != n.PreviousNode && null != n.PreviousNode.Annotation <AutoPara>()) { ((XElement)n.PreviousNode).Add(n); n.Remove(); } else { var auto = new XElement("p", n); auto.AddAnnotation(AutoPara.Default); n.ReplaceWith(auto); } } }
private static XElement EnsurePath(XElement path, XElement result) { var pathList = path.ParentsAndSelf().Reverse().ToArray(); if (pathList.Length == 0) { throw new ArgumentException(); } var curr = result; if (curr.Name != pathList[0].Name) { throw new ArgumentException(); } XElement match; foreach (var elem in pathList.Skip(1)) { match = curr.Elements().Where(e => PathMatches(elem, e)).FirstOrDefault(); if (match == null) { match = new XElement(elem.Name, elem.Attributes().Where(IsAttributeToCopy)); match.AddAnnotation(elem.Annotation <ElementKey>()); curr.Add(match); } curr = match; } return(curr); }
private Location GetIncludeElementLocation(XElement includeElement, ref string currentXmlFilePath, ref CSharpSyntaxNode originatingSyntax) { Location location = includeElement.Annotation <Location>(); if (location != null) { return(location); } // If we are not in an XML file, then we must be in a source file. Since we're traversing the XML tree in the same // order as the DocumentationCommentWalker, we can access the elements of includeElementNodes in order. if (currentXmlFilePath == null) { Debug.Assert(_nextSourceIncludeElementIndex < _sourceIncludeElementNodes.Length); Debug.Assert(originatingSyntax == null); originatingSyntax = _sourceIncludeElementNodes[_nextSourceIncludeElementIndex]; location = originatingSyntax.Location; _nextSourceIncludeElementIndex++; // #line shall not affect the base path: currentXmlFilePath = location.GetLineSpan().Path; } else { location = XmlLocation.Create(includeElement, currentXmlFilePath); } Debug.Assert(location != null); includeElement.AddAnnotation(location); return(location); }
/// <summary> /// Adds if doesn't exist /// </summary> /// <param name="file"></param> static void AddIncludeFile(XDocument doc, XElement itemGroup, string file) { var ns = doc.Root.Name.Namespace; string fileName = Path.GetFileName(file); Show($"Searching for {fileName}"); var matches = GetMatchingIncludeFiles(doc, file); if (matches.Count() > 0) { Show($"{fileName} has {matches.Count()} entries, which is invalid. Skipping.", ErrorColor); } else { file = Path.GetFileName(file); //Weird, but including the namespace is what causes it to be removed //because the parent element already has it. //https://stackoverflow.com/a/5956063/1628707 XElement include = new XElement(ns + "None"); include.AddAnnotation("Include"); include.SetAttributeValue("Include", file); itemGroup.Add(include); Show($"Added {fileName}"); } }
// Run the hist command for depot and add the results to our transactions list. Returns // true if operation succeeds, otherwise false. AcUtilsException caught and logged in // %LOCALAPPDATA%\AcTools\Logs\LatestTransactions-YYYY-MM-DD.log on hist command failure. // Exception caught and logged in same for a range of exceptions. private async static Task <bool> initLastTransAsync(string depot) { bool ret = false; // assume failure try { AcResult r = await AcCommand.runAsync($@"hist -p ""{depot}"" -t now -fx"); if (r != null && r.RetVal == 0) { XElement xml = XElement.Parse(r.CmdResult); XElement trans = xml.Element("transaction"); trans.AddAnnotation(depot); // add depot since it's not in the XML lock (_locker) { _transactions.Add(trans); } ret = true; } } catch (AcUtilsException exc) { AcDebug.Log($"AcUtilsException caught and logged in Program.initLastTransAsync{Environment.NewLine}{exc.Message}"); } catch (Exception ecx) { AcDebug.Log($"Exception caught and logged in Program.initLastTransAsync{Environment.NewLine}{ecx.Message}"); } return(ret); }
static void ApplyAnnotationToElement(XElement element, XElement annotation, object obj) { Contract.Requires <ArgumentNullException>(element != null); Contract.Requires <ArgumentNullException>(annotation != null); Contract.Requires <ArgumentNullException>(obj != null); element.AddAnnotation(obj); }
public static XTypedElement ToXTypedElement(XElement xe, ILinqToXsdTypeManager typeManager, System.Type t) { if (xe == null) { return(null); } if (!t.IsSubclassOf(typeof(XTypedElement))) { throw new InvalidOperationException("Type t is not a subtype of XTypedElement"); } if (typeManager == null) { throw new ArgumentNullException("typeManager"); } XTypedElement xoSubType = GetAnnotation(t, xe); //Try getting back as the type first, optimized for the cases where xsi:type cannot appear if (xoSubType == null) { //Try xsi:type and lookup in the typeDictionary Type clrType = GetXsiClrType(xe, typeManager); if (clrType != null) { xoSubType = GetAnnotation(clrType, xe); if (xoSubType != null) { return(xoSubType); } if (!t.IsAssignableFrom(clrType)) { //xsi:type is not subtype of schema type clrType = t; } } else { //xsi:type not present or CLRType not found for xsi:type name clrType = t; } if (clrType.IsAbstract) { throw new InvalidOperationException("Cannot cast XElement to an abstract type"); } ConstructorInfo constrInfo = clrType.GetConstructor(System.Type.EmptyTypes); xoSubType = (XTypedElement)constrInfo.Invoke(null); xoSubType.Untyped = xe; xe.AddAnnotation(new XTypedElementAnnotation(xoSubType)); } return(xoSubType); }
private static XElement CreateVBSample() { XElement e1 = new XElement("{ns1}A", new XAttribute("xmlns", "ns1")); XElement c1 = new XElement("{ns1}B", new XAttribute("xmlns", "ns1")); XElement c2 = new XElement("{ns1}C", new XAttribute("xmlns", "ns1")); e1.Add(c1, c2); e1.AddAnnotation(SaveOptions.OmitDuplicateNamespaces); return(e1); }
public static void EnsureAnnotation(this XElement element) { var sfa = element.Annotation <XmlFileAnnotation>(); if (sfa == null) { sfa = new XmlFileAnnotation(); element.AddAnnotation(sfa); } }
public async Task <IEnumerable <string> > MoveVersions( string solutionPath, XDocument packagesDocument, CancellationToken cancellationToken ) { var movedVersions = new HashSet <string>(); var projects = GetSolution(solutionPath).Projects.Values.Select(x => x) .SelectMany( projectReference => projectReference.Build().Select(project => { using var file = File.OpenRead(projectReference.ProjectFile.Path); return(path: projectReference.ProjectFile.Path, document: XDocument.Load(file, LoadOptions.PreserveWhitespace), project); })); foreach (var(path, document, project) in projects) { foreach (var item in document.Descendants("PackageReference") .Where(x => !string.IsNullOrEmpty(x.Attribute("Version")?.Value)) .ToArray() ) { _logger.LogInformation( "Found Version {Version} on {Package} in {Path} and moving it to props file", item.Attribute("Version").Value, item.Attribute("Include").Value, path ); movedVersions.Add(item.Attribute("Include").Value); var @new = new XElement(item); @new.SetAttributeValue("Update", @new.Attribute("Include").Value); @new.SetAttributeValue("Include", null); @new.SetAttributeValue("Version", null); @new.SetAttributeValue("Version", item.Attribute("Version").Value); var itemGroupToInsertInto = GetItemGroupToInsertInto(document, project, @new.Attribute("Update").Value); foreach (var an in itemGroupToInsertInto.Descendants("PackageReference").LastOrDefault() ?.Annotations <XmlSignificantWhitespace>() ?? Enumerable.Empty <XmlSignificantWhitespace>()) { @new.AddAnnotation(an); } itemGroupToInsertInto.Add(@new); item.SetAttributeValue("Version", null); } await UpdateXDocument(path, document, cancellationToken).ConfigureAwait(false); } OrderPackageReferences(packagesDocument); RemoveDuplicatePackageReferences(packagesDocument); return(movedVersions.OrderBy(x => x)); }
public static XElement AddElement(this XElement element, string name, object value, XmlSemanticAnnotation annotation, bool annotateName = false) { annotation.AppliesToName = annotateName; var child = new XElement(name); element.Add(child); child.AddAnnotation(annotation); return(element); }
public static void SetTextRange(this XElement element, ElementTextRange textRange) { var sfa = element.Annotation <XmlFileAnnotation>(); if (sfa == null) { sfa = new XmlFileAnnotation(); element.AddAnnotation(sfa); } sfa.TextRange = textRange; }
public virtual TimeSpan SynthesizeElement(XElement element, WaveFileWriter writer, string src = "") { if (element == null) { throw new ArgumentNullException(nameof(element)); } var syncAnno = SynthesizeText(element.Value, writer, src); syncAnno.Element = element; element.AddAnnotation(syncAnno); return(syncAnno.ClipEnd.Subtract(syncAnno.ClipBegin)); }
public static XTypedElement ToXTypedElement(XElement xe, ILinqToXsdTypeManager typeManager, Type t) { XTypedElement xTypedElement; if (xe != null) { if (!t.IsSubclassOf(typeof(XTypedElement))) { throw new InvalidOperationException("Type t is not a subtype of XTypedElement"); } if (typeManager == null) { throw new ArgumentNullException("typeManager"); } XTypedElement xoSubType = XTypedServices.GetAnnotation(t, xe); if (xoSubType == null) { Type clrType = XTypedServices.GetXsiClrType(xe, typeManager); if (!(clrType != null)) { clrType = t; } else { xoSubType = XTypedServices.GetAnnotation(clrType, xe); if (xoSubType != null) { xTypedElement = xoSubType; return(xTypedElement); } if (!t.IsAssignableFrom(clrType)) { clrType = t; } } if (clrType.IsAbstract) { throw new InvalidOperationException("Cannot cast XElement to an abstract type"); } ConstructorInfo constrInfo = clrType.GetConstructor(Type.EmptyTypes); xoSubType = (XTypedElement)constrInfo.Invoke(null); xoSubType.Untyped = xe; xe.AddAnnotation(new XTypedElementAnnotation(xoSubType)); } xTypedElement = xoSubType; } else { xTypedElement = null; } return(xTypedElement); }
private XElement CreateXElement() { IXMetaData schemaMetaData = this; Debug.Assert(schemaMetaData != null); XName elementName = schemaMetaData.SchemaName; Debug.Assert(elementName != null); XElement element = new XElement(elementName); element.AddAnnotation(new XTypedElementAnnotation(this)); return(element); }
private static XObject CloneWithAnnotation(XNode node) { if (node is XElement element) { var newElement = new XElement(element.Name, element.Attributes(), element.Nodes().Select(n => CloneWithAnnotation(n))); if (element.Annotation <MatchSemaphore>() != null) { newElement.AddAnnotation(element.Annotation <MatchSemaphore>()); } } return(node); }
//[Variation(Priority = 2, Desc = "Add annotation to XElement, and remove this element, get annotation")] public void Annotations_21() { string str = "element1111"; XElement root = new XElement("root"); XElement element = new XElement("elem1"); root.Add(element); element.AddAnnotation(str); element.Remove(); ValidateAnnotations <string>(element, new string[] { str }); TestLog.Compare(element.Annotation <string>(), str, "Validation failed"); TestLog.Compare(element.Annotation(typeof(string)), str, "Validation failed"); }
// Creates an <xs:element> element defining the presence of the named element // representing a class public XElement CreateXsElementForNofClass(XDocument xsdDoc, XElement element, bool addCardinality) { // gather details from XML element string localName = element.Name.LocalName; // <xs:element name="AO11ConfirmAnimalRegistration"> // <xs:complexType> // <xs:sequence> // <xs:element ref="nof:title"/> // <!-- placeholder --> // </xs:sequence> // <xs:attribute ref="nof:feature" // default="class"/> // <xs:attribute ref="nof:oid"/> // <xs:attribute ref="nof:annotation"/> // <xs:attribute ref="nof:fqn"/> // </xs:complexType> // </xs:element> // xs:element/@name="class name" // add to XML schema as a global attribute XElement xsElementForNofClassElement = XsMetaModel.CreateXsElementElement(xsdDoc, localName, addCardinality); // xs:element/xs:complexType // xs:element/xs:complexType/xs:sequence XElement xsComplexTypeElement = XsMetaModel.ComplexTypeFor(xsElementForNofClassElement); XElement xsSequenceElement = XsMetaModel.SequenceFor(xsComplexTypeElement); // xs:element/xs:complexType/xs:sequence/xs:element ref="nof:title" XElement xsTitleElement = XsMetaModel.CreateXsElement(Helper.DocFor(xsSequenceElement), "element"); xsTitleElement.SetAttributeValue("ref", NofMetaModel.NofMetamodelNsPrefix + ":" + "title"); xsSequenceElement.Add(xsTitleElement); XsMetaModel.SetXsCardinality(xsTitleElement, 0, 1); // xs:element/xs:complexType/xs:sequence/xs:element ref="extensions" //addXsElementForAppExtensions(xsSequenceElement, extensions); // xs:element/xs:complexType/xs:attribute ... XsMetaModel.AddXsNofFeatureAttributeElements(xsComplexTypeElement, "class"); XsMetaModel.AddXsNofAttribute(xsComplexTypeElement, "oid"); XsMetaModel.AddXsNofAttribute(xsComplexTypeElement, "fqn"); XsMetaModel.AddXsNofAttribute(xsComplexTypeElement, "singular"); XsMetaModel.AddXsNofAttribute(xsComplexTypeElement, "plural"); XsMetaModel.AddXsNofAttribute(xsComplexTypeElement, "annotation"); element.AddAnnotation(xsElementForNofClassElement); return(xsElementForNofClassElement); }
public static void SetName(XTypedElement root, XTypedElement type) { IXMetaData schemaMetaData = root; Debug.Assert(schemaMetaData != null); XName elementName = schemaMetaData.SchemaName; Debug.Assert(elementName != null); XElement currentElement = type.Untyped; currentElement.Name = elementName; currentElement.AddAnnotation(new XTypedElementWrapperAnnotation(root)); root.Untyped = currentElement; }
public static T CloneXTypedElement <T>(T xTypedElement) where T : XTypedElement, new() { if (xTypedElement == null) { throw new ArgumentNullException("Argument xTypedElement should not be null."); } XElement clonedElement = new XElement(xTypedElement.Untyped); T newObject = Activator.CreateInstance <T>(); newObject.Untyped = clonedElement; clonedElement.AddAnnotation(new XTypedElementAnnotation(newObject)); return(newObject); }
public static void SetParagraphLevel(XElement paragraph, int ilvl) { var pi = paragraph.Annotation <ParagraphInfo>(); if (pi == null) { pi = new ParagraphInfo() { Ilvl = ilvl, }; paragraph.AddAnnotation(pi); return; } throw new OpenXmlPowerToolsException("Internal error - should never set ilvl more than once."); }
public void AddAnnotationXElementRemoveAndGet() { // Add annotation to XElement, and remove this element, get annotation const string expected = "element1111"; XElement root = new XElement("root"); XElement element = new XElement("elem1"); root.Add(element); element.AddAnnotation(expected); element.Remove(); ValidateAnnotations(element, new string[] { expected }); Assert.Equal(expected, element.Annotation <string>()); Assert.Equal(expected, element.Annotation(typeof(string))); }