private XElement FindPropertyElement(XElement project, string propertyName) { foreach (var nemerleProperty in project.Descendants(vs + propertyName)) return nemerleProperty; // Try to add property if it's not exists foreach (var propertyGroup in project.Elements(vs + "PropertyGroup").Where(g => !g.HasAttributes)) { var text = propertyGroup.HasElements ? propertyGroup.FirstNode as XText : null; var newElem = new XElement(vs + propertyName, ""); if (propertyName == "Nemerle") propertyGroup.Add(newElem); else propertyGroup.AddFirst(newElem); if (text != null) newElem.AddBeforeSelf(text.Value); else newElem.AddBeforeSelf(" " + Environment.NewLine); return newElem; } throw new ApplicationException("Incorrect format of project file. The project must contains '" + propertyName + "' property."); }
//=========================================================================================== private void AddMagickImageCollectionMethods(XElement annotation) { foreach (MethodInfo[] overloads in _GraphicsMagickNET.GetGroupedMagickImageCollectionMethods()) { annotation.AddBeforeSelf(CreateElement(overloads)); } }
// Partially taken from https://github.com/kipusoep/UrlTracker/blob/b2bc998adaae2f74779e1119fd7b1e97a3b71ed2/UI/Installer/UrlTrackerInstallerService.asmx.cs public static bool InstallDashboard(string section, string caption, string control) { bool result = false; try { string dashboardConfig; string dashboardConfigPath = HttpContext.Current.Server.MapPath("~/config/dashboard.config"); using (StreamReader streamReader = File.OpenText(dashboardConfigPath)) dashboardConfig = streamReader.ReadToEnd(); if (string.IsNullOrEmpty(dashboardConfig)) throw new Exception("Unable to add dashboard: Couldn't read current ~/config/dashboard.config, permissions issue?"); XDocument dashboardDoc = XDocument.Parse(dashboardConfig, LoadOptions.PreserveWhitespace); if (dashboardDoc == null) throw new Exception("Unable to add dashboard: Unable to parse current ~/config/dashboard.config file, invalid XML?"); XElement dashBoardElement = dashboardDoc.Element("dashBoard"); if (dashBoardElement == null) throw new Exception("Unable to add dashboard: dashBoard element not found in ~/config/dashboard.config file"); List<XElement> sectionElements = dashBoardElement.Elements("section").ToList(); if (sectionElements == null || !sectionElements.Any()) throw new Exception("Unable to add dashboard: No section elements found in ~/config/dashboard.config file"); XElement existingSectionElement = sectionElements.SingleOrDefault(x => x.Attribute("alias") != null && x.Attribute("alias").Value == section); if (existingSectionElement == null) throw new Exception(string.Format("Unable to add dashboard: '{0}' section not found in ~/config/dashboard.config", section)); List<XElement> tabs = existingSectionElement.Elements("tab").ToList(); if (!tabs.Any()) throw new Exception(string.Format("Unable to add dashboard: No existing tabs found within the '{0}' section", section)); List<XElement> existingTabs = tabs.Where(x => x.Attribute("caption").Value == caption).ToList(); if (existingTabs.Any()) { foreach (XElement tab in existingTabs) { List<XElement> existingTabControls = tab.Elements("control").ToList(); if (existingTabControls.Any(x => x.Value == control)) return true; } } XElement lastTab = tabs.Last(); XElement newTab = new XElement("tab"); newTab.Add(new XAttribute("caption", caption)); XElement newControl = new XElement("control"); newControl.Add(new XAttribute("addPanel", true)); newControl.SetValue(control); newTab.Add(newControl); newControl.AddBeforeSelf(string.Concat(Environment.NewLine, " ")); newControl.AddAfterSelf(string.Concat(Environment.NewLine, " ")); lastTab.AddAfterSelf(newTab); lastTab.AddAfterSelf(string.Concat(Environment.NewLine, " ")); dashboardDoc.Save(dashboardConfigPath, SaveOptions.None); result = true; } catch (Exception ex) { ExceptionHelper.LogExceptionMessage(typeof(DashboardHelper), ex); } return result; }
public override void InsertPredicate( XElement target, long id, ElementType type) { var oldcode = Python3XmlToCode.Instance.Generate(target); var code = "CoverageWriter.WritePredicate(" + id + "," + (int)type + "," + oldcode + ")"; var node = Python3CodeToXml.Instance.Generate(code) .Descendants(target.Name) .First(); target.AddBeforeSelf(node); target.Remove(); }
// <?xml version="1.0"?> // <?order alpha ascending?> // <art xmlns='urn:art-org:art'> // <period name='Renaissance' xmlns:a='urn:art-org:artists'> // <a:artist>Leonardo da Vinci</a:artist> // <a:artist>Michelangelo</a:artist> // <a:artist><![CDATA[Donatello]]></a:artist> // </period> // <!-- 在此处插入 period --> // </art> public static XDocument CreateDocumentVerbose() { XNamespace nsArt = "urn:art-org:art"; XNamespace nsArtists = "urn:art-org:artists"; // 创建文档 XDocument document = new XDocument(); // 创建 xml 声明,并在 // 文档中对其进行设置 document.Declaration = new XDeclaration("1.0", null, null); // 创建 art 元素,并将其 // 添加到文档中 XElement art = new XElement(nsArt + "art"); document.Add(art); // 创建顺序处理指令,并将其 // 添加到 art 元素之前 XProcessingInstruction pi = new XProcessingInstruction("order", "alpha ascending"); art.AddBeforeSelf(pi); // 创建 period 元素,并将其 // 添加到 art 元素中 XElement period = new XElement(nsArt + "period"); art.Add(period); // 向 period 元素中添加 name 特性 period.SetAttributeValue("name", "Renaissance"); // 创建命名空间声明 xmlns:a,并将其 // 添加到 period 元素中 XAttribute nsdecl = new XAttribute(XNamespace.Xmlns + "a", nsArtists); period.Add(nsdecl); // 创建 artist 元素和 // 基础文本节点 period.SetElementValue(nsArtists + "artist", "Michelangelo"); XElement artist = new XElement(nsArtists + "artist", "Leonardo ", "da ", "Vinci"); period.AddFirst(artist); artist = new XElement(nsArtists + "artist"); period.Add(artist); XText cdata = new XText("Donatello"); artist.Add(cdata); // 创建注释,并将其 // 添加到 art 元素中 XComment comment = new XComment("insert period here"); art.Add(comment); return document; }
// <?xml version="1.0"?> // <?order alpha ascending?> // <art xmlns='urn:art-org:art'> // <period name='Renaissance' xmlns:a='urn:art-org:artists'> // <a:artist>Leonardo da Vinci</a:artist> // <a:artist>Michelangelo</a:artist> // <a:artist><![CDATA[Donatello]]></a:artist> // </period> // <!-- insert period here --> // </art> public static XDocument CreateDocumentVerbose() { XNamespace nsArt = "urn:art-org:art"; XNamespace nsArtists = "urn:art-org:artists"; // create the document XDocument document = new XDocument(); // create the xml declaration and // set on the document document.Declaration = new XDeclaration("1.0", null, null); // create the art element and // add to the document XElement art = new XElement(nsArt + "art"); document.Add(art); // create the order processing instruction and // add before the art element XProcessingInstruction pi = new XProcessingInstruction("order", "alpha ascending"); art.AddBeforeSelf(pi); // create the period element and // add to the art element XElement period = new XElement(nsArt + "period"); art.Add(period); // add the name attribute to the period element period.SetAttributeValue("name", "Renaissance"); // create the namespace declaration xmlns:a and // add to the period element XAttribute nsdecl = new XAttribute(XNamespace.Xmlns + "a", nsArtists); period.Add(nsdecl); // create the artists elements and // the underlying text nodes period.SetElementValue(nsArtists + "artist", "Michelangelo"); XElement artist = new XElement(nsArtists + "artist", "Leonardo ", "da ", "Vinci"); period.AddFirst(artist); artist = new XElement(nsArtists + "artist"); period.Add(artist); XText cdata = new XText("Donatello"); artist.Add(cdata); // create the comment and // add to the art element XComment comment = new XComment("insert period here"); art.Add(comment); return document; }
private void ReplaceValues(XElement dynamicRow) { var readers = DataReader.GetReaders(TableTag.ItemsSource).ToList(); for (var index = 0; index < readers.Count(); index++) { var currentRow = new XElement(dynamicRow); var tableElements = TableTag.MakeTableElementCallback(currentRow); this.ProcessElements(tableElements, readers[index], index+1, null, true); dynamicRow.AddBeforeSelf(currentRow); } dynamicRow.Remove(); }
public override void InsertPredicate(XElement target, long id, ElementType type) { var node = new XElement("call", new object[] { new XElement("nil"), new XElement("Symbol", "branch"), new XElement("lit", new[] { new XElement("Fixnum", id), }), new XElement("lit", new[] { new XElement("Fixnum", (int)type), }), target, }); target.AddBeforeSelf(node); target.Remove(); }
/// <summary> /// Clears any <see cref="XComment"/> or <see cref="XText"/> nodes before /// this one. /// </summary> /// <param name="this">This element.</param> /// <returns>This element (fluent syntax).</returns> public static XElement ClearCommentsBefore(this XElement @this) { bool hasNewLine = false; @this.NodesBeforeSelf() .Reverse() .TakeWhile(n => n is XComment || n is XText) .Reverse() .Select(n => { hasNewLine |= n is XText t && t.Value.IndexOf('\n') >= 0; return(n); }) .Remove(); if (hasNewLine) { @this.AddBeforeSelf(Environment.NewLine); } return(@this); }
/// <summary> /// Tests AddBeforeSelf on Node. /// </summary> /// <param name="context"></param> /// <returns></returns> //[Variation(Desc = "NodeAddBeforeSelf")] public void NodeAddBeforeSelf() { XElement parent = new XElement("parent"); XElement child = new XElement("child"); parent.Add(child); XElement sibling1 = new XElement("sibling1"); XComment sibling2 = new XComment("sibling2"); XText sibling3 = new XText("sibling3"); child.AddBeforeSelf(sibling1); Validate.EnumeratorDeepEquals(parent.Nodes(), new XNode[] { sibling1, child }); child.AddBeforeSelf(sibling2, sibling3); Validate.EnumeratorDeepEquals( parent.Nodes(), new XNode[] { sibling1, sibling2, sibling3, child }); }
void DoInlineImport(XElement import, InlineImport inlineImport) { var importPath = ExpandPath(SourceDirectory, import.Attribute("Project").Value); var inlinedDoc = XDocument.Load(importPath); RelocateImports(Path.GetDirectoryName(importPath), inlinedDoc); var project = inlinedDoc.Root; List<XNode> filteredNodes = new List<XNode>(); bool inSample = true; foreach (var node in project.Nodes()) { if (node is XComment) { var comment = (XComment)node; if (comment.Value.Contains("[[NOT IN SAMPLE]]")) { inSample = false; continue; } else if (comment.Value.Contains("[[IN SAMPLE]]")) { inSample = true; continue; } } if (inSample) filteredNodes.Add(node); } import.AddBeforeSelf(filteredNodes); if (inlineImport.Elements.Count > 0) { import.AddBeforeSelf(inlineImport.Elements); } import.Remove(); }
public static void transform_selection(XElement xml) { var sels = xml.Descendants(exFile.lm + "selection").ToArray(); //html titles se daji pred selection, BT 2149 var htmlTits = sels.SelectMany(s => s.Attributes("title_html")).ToArray(); Dictionary<string, XElement> htmlTitles = null; if (htmlTits.Length > 0) { htmlTitles = xml.Descendants().Select(el => new { el, id = el.AttributeValue("id") }).Where(a => a.id != null).ToDictionary(a => a.id, a => a.el); } XAttribute attrBuf; foreach (var sel in sels) { bool isRadio = sel.AttributeValue("type") == "radioButton"; if (isRadio) { string title = sel.AttributeValue("title"); string htmlTitle = sel.AttributeValue("title_html"); sel.AddBeforeSelf(new XComment(sel.ToString())); XElement newSel; sel.AddBeforeSelf( new XElement(exFile.lm + "control", // string.IsNullOrEmpty(title) ? null : new XElement(exFile.html + "header-prop", new XElement(exFile.html + "h4", title)), string.IsNullOrEmpty(title) ? null : new XElement(exFile.html + "h4", title), newSel = new XElement(exFile.html + "single-choice", (attrBuf = sel.Attribute("id")) == null ? null : new XAttribute("id", attrBuf.Value), sel.Elements().Select(cb => new XElement(exFile.html + "radio-button", (attrBuf = cb.Attribute("id")) == null ? null : new XAttribute("id", attrBuf.Value), cb.AttributeValue("title"), cb.AttributeValue("init_value") == "Checked" ? new XAttribute("init-value", "true") : null, (attrBuf = cb.Attribute("correct")) == null ? null : new XAttribute("correct-value", attrBuf.Value) ))))); if (htmlTitle != null) { htmlTitles[htmlTitle].Remove(); newSel.AddBeforeSelf(htmlTitles[htmlTitle]); } var isEx = sel.Elements().Any(cb => new string[] { "true", "1" }.Contains(cb.AttributeValue("example"))); var isInit = sel.Elements().Any(cb => cb.AttributeValue("init_value") == "Checked"); if (isEx) { newSel.Add(isInit ? new XAttribute("read-only", "true") : new XAttribute("skip-evaluation", "true")); } } else { string title = sel.AttributeValue("title"); string htmlTitle = sel.AttributeValue("title_html"); sel.AddBeforeSelf(new XComment(sel.ToString())); var id = sel.AttributeValue("id"); //XElement newSel; sel.AddBeforeSelf( new XElement(exFile.lm + "control", string.IsNullOrEmpty(title) ? null : new XElement(exFile.html + "h4", title), htmlTitle == null ? null : htmlTitles[htmlTitle], sel.Elements().Select(cb => new XElement(exFile.html + "check-item", new XAttribute("text-type", "no"), (attrBuf = cb.Attribute("id")) == null ? null : new XAttribute("id", attrBuf.Value), cb.AttributeValue("title"), cb.AttributeValue("eval_group") == "And" && !string.IsNullOrEmpty(id) ? new XAttribute("eval-group", "and-" + id) : null, cb.AttributeValue("init_value") == "Checked" ? new XAttribute("init-value", "True") : null, (attrBuf = cb.Attribute("correct")) == null ? null : new XAttribute("correct-value", attrBuf.Value) )))); if (htmlTitle != null) htmlTitles[htmlTitle].Remove(); } sel.Remove(); } //if (htmlTitles != null) htmlTitles.Values.Remove(); }
public void NodeAddBeforeSelf() { XElement parent = new XElement("parent"); XElement child = new XElement("child"); parent.Add(child); XElement sibling1 = new XElement("sibling1"); XComment sibling2 = new XComment("sibling2"); XText sibling3 = new XText("sibling3"); child.AddBeforeSelf(sibling1); Assert.Equal(new XNode[] { sibling1, child }, parent.Nodes(), XNode.EqualityComparer); child.AddBeforeSelf(sibling2, sibling3); Assert.Equal(new XNode[] { sibling1, sibling2, sibling3, child }, parent.Nodes(), XNode.EqualityComparer); }
//=========================================================================================== private void ReplaceEnums(XElement annotation) { foreach (Type enumType in _GraphicsMagickNET.Enums) { annotation.AddBeforeSelf(CreateEnumElement(enumType)); } annotation.Remove(); }
private void ReplaceDrawables(XElement annotation) { foreach (ConstructorInfo[] constructors in _Types.GetDrawables()) { annotation.AddBeforeSelf(CreateElement(constructors)); } annotation.Remove(); }
void CheckConnectionId(XamlContext ctx, XElement elem, Dictionary<int, Action<XamlContext, XElement>> connIds) { var connId = elem.Annotation<BamlConnectionId>(); if (connId == null) return; Action<XamlContext, XElement> cb; if (!connIds.TryGetValue((int)connId.Id, out cb)) { elem.AddBeforeSelf(new XComment(string.Format(dnSpy_BamlDecompiler_Resources.Error_UnknownConnectionId, connId.Id))); return; } cb(ctx, elem); }
public void Callback(XamlContext ctx, XElement elem) { elem.AddBeforeSelf(new XComment(Msg)); }
public static void PreprocessCodeBlocksToPreTags(GeneratorOptions options, XDocument doc) { var nodesToRemove = new List<XElement>(); var codeNodes = doc.XPathSelectElements("//code"); foreach (var codeNode in codeNodes) { string processedCodeSample = null; var xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "source"); if (xattribute != null) { var sourceRelativePath = xattribute.Value; xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "region"); if (xattribute == null) continue; var regionName = xattribute.Value; var samplePath = FindSampleCodePath(options.CodeSamplesRootFolder, sourceRelativePath); if (samplePath == null) { Console.Error.WriteLine("Error finding sample path for {0}", sourceRelativePath); continue; } var content = File.ReadAllText(samplePath); var startPos = content.IndexOf("#region " + regionName); if (startPos == -1) { Console.Error.WriteLine("Error finding region for {0}", regionName); continue; } startPos = content.IndexOf('\n', startPos); var endPos = content.IndexOf("#endregion", startPos); processedCodeSample = content.Substring(startPos, endPos - startPos); } else { processedCodeSample = codeNode.Value; } if (processedCodeSample != null && processedCodeSample.IndexOf('\n') > -1) { processedCodeSample = LeftJustifyCodeBlocks(processedCodeSample); var preElement = new XElement("pre", processedCodeSample); preElement.SetAttributeValue("class", "brush: csharp"); codeNode.AddAfterSelf(preElement); nodesToRemove.Add(codeNode); string title = null; xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "title"); if (xattribute != null) title = xattribute.Value; if (title != null) { var titleElement = new XElement("h4", title); titleElement.SetAttributeValue("class", "csharp-code-sample-title"); preElement.AddBeforeSelf(titleElement); } } } nodesToRemove.ForEach(x => x.Remove()); }
//=========================================================================================== private void AddMagickImageProperties(XElement annotation) { foreach (PropertyInfo property in _GraphicsMagickNET.GetMagickImageProperties()) { annotation.AddBeforeSelf(CreateElement(property)); } }
private void ReplaceEnums(XElement annotation) { foreach (Type enumType in _Types.GetEnums()) { annotation.AddBeforeSelf(CreateEnumElement(enumType)); } annotation.Remove(); }
//=========================================================================================== private void ReplacePaths(XElement annotation) { foreach (ConstructorInfo[] constructors in _GraphicsMagickNET.GetPaths()) { annotation.AddBeforeSelf(CreateElement(constructors)); } annotation.Remove(); }
public static void AddToc(WordprocessingDocument doc, XElement addBefore, string switches, string title, int? rightTabPos) { UpdateFontTablePart(doc); UpdateStylesPartForToc(doc); UpdateStylesWithEffectsPartForToc(doc); if (title == null) title = "Contents"; if (rightTabPos == null) rightTabPos = 9350; // {0} tocTitle (default = "Contents") // {1} rightTabPosition (default = 9350) // {2} switches String xmlString = @"<w:sdt xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'> <w:sdtPr> <w:docPartObj> <w:docPartGallery w:val='Table of Contents'/> <w:docPartUnique/> </w:docPartObj> </w:sdtPr> <w:sdtEndPr> <w:rPr> <w:rFonts w:asciiTheme='minorHAnsi' w:cstheme='minorBidi' w:eastAsiaTheme='minorHAnsi' w:hAnsiTheme='minorHAnsi'/> <w:color w:val='auto'/> <w:sz w:val='22'/> <w:szCs w:val='22'/> <w:lang w:eastAsia='en-US'/> </w:rPr> </w:sdtEndPr> <w:sdtContent> <w:p> <w:pPr> <w:pStyle w:val='TOCHeading'/> </w:pPr> <w:r> <w:t>{0}</w:t> </w:r> </w:p> <w:p> <w:pPr> <w:pStyle w:val='TOC1'/> <w:tabs> <w:tab w:val='right' w:leader='dot' w:pos='{1}'/> </w:tabs> <w:rPr> <w:noProof/> </w:rPr> </w:pPr> <w:r> <w:fldChar w:fldCharType='begin' w:dirty='true'/> </w:r> <w:r> <w:instrText xml:space='preserve'> {2} </w:instrText> </w:r> <w:r> <w:fldChar w:fldCharType='separate'/> </w:r> </w:p> <w:p> <w:r> <w:rPr> <w:b/> <w:bCs/> <w:noProof/> </w:rPr> <w:fldChar w:fldCharType='end'/> </w:r> </w:p> </w:sdtContent> </w:sdt>"; XElement sdt = XElement.Parse(String.Format(xmlString, title, rightTabPos, switches)); XDocument mainXDoc = doc.MainDocumentPart.GetXDocument(); addBefore.AddBeforeSelf(sdt); doc.MainDocumentPart.PutXDocument(); XDocument settingsXDoc = doc.MainDocumentPart.DocumentSettingsPart.GetXDocument(); XElement updateFields = settingsXDoc.Descendants(W.updateFields).FirstOrDefault(); if (updateFields != null) updateFields.Attribute(W.val).Value = "true"; else { updateFields = new XElement(W.updateFields, new XAttribute(W.val, "true")); settingsXDoc.Root.Add(updateFields); } doc.MainDocumentPart.DocumentSettingsPart.PutXDocument(); }
/// <summary> /// Apply the formatting from a span including all nested spans to each run contained within it /// </summary> /// <param name="span">The root span from which to start applying formatting</param> /// <param name="runProps">The run properties in which to accumulate formatting</param> private static void ApplySpanFormatting(XElement span, XElement runProps) { string spanClass = (string)span.Attribute("class"); switch(spanClass) { case null: // Missing class name, ignore it. Shouldn't see any at this point, but just in case. break; case "languageSpecificText": // Replace language-specific text with the neutral text sub-entry. If not found, remove it. var genericText = span.Elements("span").FirstOrDefault(s => (string)s.Attribute("class") == "nu"); if(genericText != null) span.ReplaceWith(new XElement(w + "r", new XElement(w + "t", genericText.Value))); else span.Remove(); return; case "Bold": case "nolink": case "NoLink": case "selflink": case "SelfLink": if(!runProps.Elements(w + "b").Any()) runProps.Add(new XElement(w + "b")); break; case "Emphasis": if(!runProps.Elements(w + "i").Any()) runProps.Add(new XElement(w + "i")); break; case "Underline": if(!runProps.Elements(w + "u").Any()) runProps.Add(new XElement(w + "u", new XAttribute(w + "val", "single"))); break; case "Subscript": // If vertAlign exists, replace it as we can't merge it var subscript = runProps.Elements(w + "vertAlign").FirstOrDefault(); if(subscript != null) subscript.Attribute(w + "val").Value = "subscript"; else runProps.Add(new XElement(w + "vertAlign", new XAttribute(w + "val", "subscript"))); break; case "Superscript": // If vertAlign exists, replace it as we can't merge it var superscript = runProps.Elements(w + "vertAlign").FirstOrDefault(); if(superscript != null) superscript.Attribute(w + "val").Value = "superscript"; else runProps.Add(new XElement(w + "vertAlign", new XAttribute(w + "val", "superscript"))); break; default: // Named style // Correct the casing on code and syntax section style names switch(spanClass) { case "comment": case "identifier": case "keyword": case "literal": case "parameter": case "typeparameter": spanClass = spanClass[0].ToString().ToUpperInvariant() + spanClass.Substring(1); break; default: break; } // If one exists, replace it since we can't merge them var namedStyle = runProps.Elements(w + "rStyle").FirstOrDefault(); if(namedStyle != null) namedStyle.Attribute(w + "val").Value = spanClass; else runProps.Add(new XElement(w + "rStyle", new XAttribute(w + "val", spanClass))); break; } // If the span does not have children but is not empty, it has inner text that needs to be wrapped // in a run. if(!span.HasElements && !span.IsEmpty) { var content = new XElement(w + "r", new XElement(w + "t", new XAttribute(XNamespace.Xml + "space", "preserve"), span.Value)); span.Value = String.Empty; span.Add(content); } // Add the run properties to each child run foreach(var run in span.Elements(w + "r")) run.AddFirst(new XElement(runProps)); // Handle nested spans. These will accumulate the formatting of the parent spans. foreach(var nestedSpan in span.Elements("span").ToList()) ApplySpanFormatting(nestedSpan, new XElement(runProps)); // Now move the content up to the parent foreach(var child in span.Nodes().ToList()) { child.Remove(); span.AddBeforeSelf(child); } // And finally, remove the span span.Remove(); }
public static void AddTof(WordprocessingDocument doc, XElement addBefore, string switches, int? rightTabPos) { UpdateFontTablePart(doc); UpdateStylesPartForTof(doc); UpdateStylesWithEffectsPartForTof(doc); if (rightTabPos == null) rightTabPos = 9350; // {0} rightTabPosition (default = 9350) // {1} switches string xmlString = @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'> <w:pPr> <w:pStyle w:val='TableofFigures'/> <w:tabs> <w:tab w:val='right' w:leader='dot' w:pos='{0}'/> </w:tabs> <w:rPr> <w:noProof/> </w:rPr> </w:pPr> <w:r> <w:fldChar w:fldCharType='begin' dirty='true'/> </w:r> <w:r> <w:instrText xml:space='preserve'> {1} </w:instrText> </w:r> <w:r> <w:fldChar w:fldCharType='separate'/> </w:r> <w:r> <w:fldChar w:fldCharType='end'/> </w:r> </w:p>"; XElement paragraph = XElement.Parse(String.Format(xmlString, rightTabPos, switches)); XDocument mainXDoc = doc.MainDocumentPart.GetXDocument(); addBefore.AddBeforeSelf(paragraph); doc.MainDocumentPart.PutXDocument(); XDocument settingsXDoc = doc.MainDocumentPart.DocumentSettingsPart.GetXDocument(); XElement updateFields = settingsXDoc.Descendants(W.updateFields).FirstOrDefault(); if (updateFields != null) updateFields.Attribute(W.val).Value = "true"; else { updateFields = new XElement(W.updateFields, new XAttribute(W.val, "true")); settingsXDoc.Root.Add(updateFields); } doc.MainDocumentPart.DocumentSettingsPart.PutXDocument(); }
private void AddMagickImageMethods(XElement annotation) { foreach (MethodInfo[] overloads in _Types.GetGroupedMagickImageMethods()) { annotation.AddBeforeSelf(CreateElement(overloads)); } }
public void InsertStatementBefore( XElement target, long id, int value, ElementType type) { target.AddBeforeSelf(CreateStatementNode(target, id, value, type)); }
public string InstallDashboard() { try { Wait(); string dashboardConfig; string dashboardConfigPath = HttpContext.Current.Server.MapPath("~/config/dashboard.config"); using (StreamReader streamReader = File.OpenText(dashboardConfigPath)) dashboardConfig = streamReader.ReadToEnd(); if (string.IsNullOrEmpty(dashboardConfig)) throw new Exception("Unable to add dashboard: Couldn't read current ~/config/dashboard.config, permissions issue?"); XDocument dashboardDoc = XDocument.Parse(dashboardConfig, LoadOptions.PreserveWhitespace); if (dashboardDoc == null) throw new Exception("Unable to add dashboard: Unable to parse current ~/config/dashboard.config file, invalid XML?"); XElement dashBoardElement = dashboardDoc.Element("dashBoard"); if (dashBoardElement == null) throw new Exception("Unable to add dashboard: dashBoard element not found in ~/config/dashboard.config file"); List<XElement> sectionElements = dashBoardElement.Elements("section").ToList(); if (sectionElements == null || !sectionElements.Any()) throw new Exception("Unable to add dashboard: No section elements found in ~/config/dashboard.config file"); XElement startupDashboardSectionElement = sectionElements.SingleOrDefault(x => x.Attribute("alias") != null && x.Attribute("alias").Value == "StartupDashboardSection"); if (startupDashboardSectionElement == null) throw new Exception("Unable to add dashboard: StartupDashboardSection not found in ~/config/dashboard.config"); List<XElement> tabs = startupDashboardSectionElement.Elements("tab").ToList(); if (!tabs.Any()) throw new Exception("Unable to add dashboard: No existing tabs found within the StartupDashboardSection"); List<XElement> urlTrackerTabs = tabs.Where(x => x.Attribute("caption").Value == "Url Tracker").ToList(); if (urlTrackerTabs.Any()) { foreach (XElement tab in urlTrackerTabs) { List<XElement> urlTrackerTabControls = tab.Elements("control").ToList(); if (urlTrackerTabControls.Any(x => x.Value == "/Umbraco/UrlTracker/InfoCaster.Umbraco.UrlTracker.UI.UrlTrackerManagerWrapper.ascx")) throw new Exception("Dashboard is already installed."); } } XElement lastTab = tabs.Last(); XElement urlTrackerTab = new XElement("tab"); urlTrackerTab.Add(new XAttribute("caption", "Url Tracker")); XElement urlTrackerControl = new XElement("control"); urlTrackerControl.Add(new XAttribute("addPanel", true)); urlTrackerControl.SetValue("/Umbraco/UrlTracker/InfoCaster.Umbraco.UrlTracker.UI.UrlTrackerManagerWrapper.ascx"); urlTrackerTab.Add(urlTrackerControl); urlTrackerControl.AddBeforeSelf(string.Concat(Environment.NewLine, " ")); urlTrackerControl.AddAfterSelf(string.Concat(Environment.NewLine, " ")); lastTab.AddAfterSelf(urlTrackerTab); lastTab.AddAfterSelf(string.Concat(Environment.NewLine, " ")); dashboardDoc.Save(dashboardConfigPath, SaveOptions.None); } catch (Exception ex) { return HandleException(ex); } return string.Empty; }
void CheckConnectionId(XamlContext ctx, XElement elem, Dictionary<int, Action<XamlContext, XElement>> connIds) { var connId = elem.Annotation<BamlConnectionId>(); if (connId == null) return; Action<XamlContext, XElement> cb; if (!connIds.TryGetValue((int)connId.Id, out cb)) { elem.AddBeforeSelf(new XComment("Unknown connection ID: " + connId.Id)); return; } cb(ctx, elem); }
public void SynchronizeSmilParToWordLevel(XElement smilPar) { var smilText = smilPar.Element("text"); if (smilText == null) { FireSyncWarning("Found no child <text> of smil par", null, smilPar); return; } if (smilText.Attribute("id") == null || String.IsNullOrWhiteSpace(smilText.Attribute("id").Value)) { FireSyncWarning("id is missing from smil text", null, smilText); return; } var textElem = GetTextElement(smilText); if (textElem == null) { FireSyncWarning( String.Format("Found no text file element matching src {0}", smilText.Attributes("src").Select(a => a.Value).FirstOrDefault() ?? ""), null, smilText); return; } if (!XmlUtils.AddWordMarkup(textElem, textElem.Name.Namespace + "span", "word", true)) { return; } var lang = textElem.AncestorsAndSelf().Attributes("lang").Select(a => a.Value).FirstOrDefault(); var syncer = GetXmlSynchronizer(lang); if (syncer == null) { FireSyncWarning("Could not get synchronizer for language " + (lang ?? "<null>"), textElem, smilText); return; } var textFileUri = XmlUtils.GetPathPart(smilText.Attribute("src")); var parSyncPoint = GetSyncPointFromSmilPar(smilPar, textElem); var audioSrc = smilPar.Descendants("audio").Attributes("src").Select(a => a.Value).First(); if (parSyncPoint == null) { return;//SyncWarning has already been fired } var syncPoints = syncer.Synchronize(textElem, parSyncPoint.AudioFile, parSyncPoint.ClipBegin, parSyncPoint.ClipEnd, "word"); foreach (var id in syncPoints.Keys.Where(k => syncPoints[k].ClipBegin>=syncPoints[k].ClipEnd).ToList()) { syncPoints.Remove(id); } if (syncPoints.Values.Count(sp => sp.ClipBegin < sp.ClipEnd) <= 1) return; var oldSmilParId = smilPar.Attributes("id").Select(a => a.Value).FirstOrDefault(); var oldSmilTextId = smilPar.Descendants("text").Attributes("id").Select(a => a.Value).FirstOrDefault(); XElement firstPar = null, firstText = null; smilPar.RemoveAttributes(); smilPar.RemoveNodes(); foreach (var sp in syncPoints.Values.OrderBy(o => o)) { var newText = new XElement( "text", new XAttribute("src", String.Concat(textFileUri, "#", sp.Id))); if (firstText == null) { firstText = newText; } var newPar = new XElement( "par", new XAttribute("endsync", "last"), newText, new XElement( "audio", new XAttribute("clip-begin", DAISYUtils.GetClipAttributeValue(sp.ClipBegin)), new XAttribute("clip-end", DAISYUtils.GetClipAttributeValue(sp.ClipEnd)), new XAttribute("src", audioSrc))); if (firstPar == null) { firstPar = newPar; } smilPar.AddBeforeSelf(newPar); newText.SetAttributeValue("id", XmlUtils.GetId(newText.Document, sp.Id)); } smilPar.Remove(); if (oldSmilParId != null && firstPar != null) { firstPar.SetAttributeValue("id", oldSmilParId); } if (oldSmilTextId != null && firstText != null) { firstText.SetAttributeValue("id", oldSmilTextId); } }
private static void ExtractGeometries(XElement drawingGroupElement) { //get Name of DrawingGroup var nameDg = drawingGroupElement.Attribute(nsx + "Key").Value; var name = nameDg.Replace("DrawingGroup", ""); //find this: <GeometryDrawing Brush="{DynamicResource _3d_view_icon_BrushColor}" Geometry="F1 M512,512z M0,0z M436.631,207.445L436.631,298.319z" /> //var geos = drawingGroupElement.XPathSelectElements(".//defns:GeometryDrawing/@defns:Geometry", _nsManager).ToList(); var geos = drawingGroupElement.Descendants() .Where(e => e.Name.LocalName == "GeometryDrawing") .SelectMany(e => e.Attributes()) .Where(a => a.Name.LocalName == "Geometry") .ToList(); foreach (var geo in geos) { //build resourcename var localName = geos.Count > 1 ? string.Format("{0}Geometry{1}", name, geos.IndexOf(geo) + 1) : string.Format("{0}Geometry", name); //dont add number if only one Geometry //Add this: <Geometry x:Key="cloud_3_iconGeometry">F1 M512,512z M0,0z M409.338,216.254C398.922,351.523z</Geometry> drawingGroupElement.AddBeforeSelf(new XElement(nsDef+"Geometry", new XAttribute(nsx + "Key", localName), geo.Value)); geo.Value = string.Format("{{StaticResource {0}}}", localName); } }
/// <summary> /// This applies formatting to each nested list and list item /// </summary> /// <param name="list">The list to process</param> /// <param name="level">The level of this list</param> private void ApplyListFormatting(XElement list, int level) { NumberingStyle numStyle; string style; int start = -1, id = 1; if(level > 8) level = 8; // Handle nested lists first ignoring those that got processed in a recursive call (no parent) foreach(var nestedList in list.Descendants("ul").ToList()) if(nestedList.Parent != null) this.ApplyListFormatting(nestedList, level + 1); style = (string)list.Attribute("class"); if(!String.IsNullOrWhiteSpace(style) && style != "bullet") { if(style == "number") style = "ordered"; if(style == "ordered" && !Int32.TryParse((string)list.Attribute("start"), out start)) start = 1; // Reuse an existing bullet style override or add a new one. Numbered lists always get a new one // so that numbering starts at the expected value. if(style == "ordered") numStyle = null; else numStyle = numberingStyles.FirstOrDefault(s => s.Style == style && s.Level == level && s.Start == start); if(numStyle != null) id = numStyle.Id; else { // Style ID #1 is always the default style id = numberingStyles.Count + 2; numberingStyles.Add(new NumberingStyle { Id = id, Style = style, Level = level, Start = start }); } } foreach(var listItem in list.Elements("li").ToList()) { bool isFirstPara = true; foreach(var para in listItem.Elements(w + "p")) { var props = para.Element(w + "pPr"); if(props == null) { props = new XElement(w + "pPr"); para.AddFirst(props); } var pStyle = props.Element(w + "pStyle"); // If there is a style and it is ListParagraph, it's probably a nested list element that has // been moved up. If so, leave it alone. if(pStyle == null || (string)pStyle.Attribute(w + "val") != "ListParagraph") { if(pStyle != null) pStyle.Attribute(w + "val").Value = "ListParagraph"; else props.AddFirst(new XElement(w + "pStyle", new XAttribute(w + "val", "ListParagraph"))); // Only apply the numbering style to the first paragraph. Subsequent paragraphs in the // list item will be indented but won't have a bullet/number to mimic HTML. if(isFirstPara) { props.Add(new XElement(w + "numPr", new XElement(w + "ilvl", new XAttribute(w + "val", level.ToString(CultureInfo.InvariantCulture))), new XElement(w + "numId", new XAttribute(w + "val", id.ToString(CultureInfo.InvariantCulture))))); isFirstPara = false; } // Each paragraph turns off contextual spacing and adds an appropriate indent. Note that // we're making an assumption here about the indent widths based on the default style // sheet. props.Add( new XElement(w + "contextualSpacing", new XAttribute(w + "val", "0")), new XElement(w + "ind", new XAttribute(w + "left", ((level + 1) * 720).ToString(CultureInfo.InvariantCulture)))); } } // Adjust the indent and width on any tables within the list item. As above, we're making an // assumption about the indent widths based on the default style sheet. foreach(var para in listItem.Elements(w + "tbl")) { var props = para.Element(w + "tblPr"); if(props == null) { props = new XElement(w + "tblPr"); para.AddFirst(props); } var indent = props.Element(w + "tblInd"); // Don't replace the indent in case it was set for a nested list if(indent == null) { props.Add(new XElement(w + "tblInd", new XAttribute(w + "w", ((level + 1) * 720).ToString(CultureInfo.InvariantCulture)), new XAttribute(w + "type", "dxa"))); var width = props.Element(w + "tblW"); if(width != null) width.Attribute(w + "w").Value = (5000 - ((level + 1) * 430)).ToString(CultureInfo.InvariantCulture); } } // Move all of the list item content up into the parent and remove the list item container foreach(var child in listItem.Nodes().ToList()) { child.Remove(); listItem.AddBeforeSelf(child); } listItem.Remove(); } // Move all of the list content up into the parent and remove the list container foreach(var child in list.Nodes().ToList()) { child.Remove(); list.AddBeforeSelf(child); } list.Remove(); }