Here are the examples of the csharp api System.Xml.Linq.XContainer.AddFirst(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
23 Examples
19
Source : Container.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
public Table InsertTable(int index, int rowCount, int columnCount)
{
XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Doreplacedent, index);
if (p == null)
Xml.Elements().First().AddFirst(newTable);
else
{
XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
p.Xml.ReplaceWith
(
split[0],
newTable,
split[1]
);
}
return new Table(Doreplacedent, newTable);
}
19
Source : PList.cs
with GNU Lesser General Public License v3.0
from Egomotion
with GNU Lesser General Public License v3.0
from Egomotion
public bool Save(string pathToSaveFile, bool overwrite = false)
{
if (!IsValidPath(pathToSaveFile))
{
Debug.LogError("EgoXproject: Invalid Save Path: " + pathToSaveFile);
return false;
}
if (!overwrite)
{
if (_path != pathToSaveFile && File.Exists(pathToSaveFile))
{
Debug.LogError("EgoXproject: File exists: " + pathToSaveFile);
return false;
}
}
XDoreplacedent doc = new XDoreplacedent(_decl);
bool dtd = false;
if (_loaded)
{
if (_usedDocType != null)
{
doc.AddFirst(_usedDocType);
dtd = true;
}
}
else
{
doc.AddFirst(_docType);
dtd = true;
}
XElement plist = new XElement("plist");
plist.SetAttributeValue("version", _version);
plist.Add(_dict.Xml());
doc.Add(plist);
var stringWriter = new Utf8StringWriter();
doc.Save(stringWriter);
var content = stringWriter.GetStringBuilder().ToString();
//http://stackoverflow.com/questions/10303315/convert-stringwriter-to-string
string[] separator = { System.Environment.NewLine };
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
//Remove the spurious [] that get added to DOCTYPE. Grrr.
if (dtd)
{
for (int ii = 0; ii < lines.Length; ii++)
{
var line = lines[ii];
if (line.Contains("<!DOCTYPE") && line.Contains("[]"))
{
lines[ii] = line.Replace("[]", "");
break;
}
}
}
File.WriteAllLines(pathToSaveFile, lines);
//TODO this is a crap check.
bool bSaved = File.Exists(pathToSaveFile);
if (bSaved)
{
_path = pathToSaveFile;
}
return bSaved;
}
19
Source : Translation.cs
with MIT License
from FelisDiligens
with MIT License
from FelisDiligens
public void Save(string fileName, string version)
{
string newFileName = fileName;
string newFilePath = Path.Combine(Localization.LanguageFolder, newFileName);
// Create doreplacedent and root:
XDoreplacedent xmlDoc = new XDoreplacedent();
XElement xmlRoot = new XElement("Language");
xmlRoot.Add(new XAttribute("name", this.Name));
xmlRoot.Add(new XAttribute("iso", this.ISO));
if (this.ISO != "en-US" && this.Author.Length > 0)
xmlRoot.Add(new XAttribute("author", this.Author));
if (this.ISO == "en-US")
xmlDoc.AddFirst(
new XComment("\n" +
" This file is auto-generated on program start.\n" +
" Therefore any changes made to this file will be overwritten.\n" +
" You can use this as a template for your own translation, though.\n" +
"\n" +
" If you need help with translating, you can find a guide here:\n" +
" https://github.com/FelisDiligens/Fallout76-QuickConfiguration/wiki/Translations\n"));
else
xmlDoc.AddFirst(
new XComment("\n" +
" This is a template that contains some of the already translated elements.\n" +
" You can rename it from \"*.template.xml\" to \"*.xml\" and translate the added elements.\n" +
"\n" +
" If you need help with translating, you can find a guide here:\n" +
" https://github.com/FelisDiligens/Fallout76-QuickConfiguration/wiki/Translations\n"));
xmlRoot.Add(new XAttribute("version", version));
xmlDoc.Add(xmlRoot);
// Serialize external stuff:
// TODO: Find a way to remove the references, plz:
XElement xmlStrings = Localization.SerializeStrings();
XElement xmlDropDowns = DropDown.SerializeAll();
XElement xmlMsgBoxes = MsgBox.SerializeAll();
XElement xmlDescriptions = LinkedTweaks.SerializeTweakDescriptionList();
string separator = "".PadLeft(150, '*');
xmlStrings.AddFirst(new XComment($"\n Strings\n {separator}\n Basically little text snippets that can be used everywhere.\n "));
xmlDropDowns.AddFirst(new XComment($"\n Dropdowns\n {separator}\n Make sure that the amount of options stays the same.\n "));
xmlMsgBoxes.AddFirst(new XComment($"\n Message boxes\n {separator}\n The {"{0}"} is a placeholder, btw.\n "));
xmlDescriptions.AddFirst(new XComment($"\n Descriptions\n {separator}\n These are the descriptions of almost all tweaks.\n They appear in tool tips, when the user hovers over a tweak with the mouse cursor.\n "));
xmlRoot.Add(xmlStrings);
xmlRoot.Add(xmlDropDowns);
xmlRoot.Add(xmlMsgBoxes);
xmlRoot.Add(xmlDescriptions);
ignoreTooltipsOfTheseControls = LinkedTweaks.GetListOfLinkedControlNames();
// Serialize all control elements:
foreach (LocalizedForm form in Localization.LocalizedForms)
{
XElement xmlForm = new XElement(form.Form.Name, new XAttribute("replacedle", form.Form.Text));
xmlForm.AddFirst(new XComment($"\n {form.Form.Name}\n {separator}\n {form.Form.Text}\n "));
SerializeControls(xmlForm, form.Form, form.ToolTip);
foreach (Control control in form.SpecialControls)
SerializeControl(xmlForm, control, form.ToolTip);
xmlRoot.Add(xmlForm);
}
// Save it:
Directory.CreateDirectory(Localization.LanguageFolder);
xmlDoc.Save(newFilePath);
}
19
Source : LegacyManagedMods.cs
with MIT License
from FelisDiligens
with MIT License
from FelisDiligens
public static void GenerateLegacyXML(ManagedMods mods)
{
// I ported the old Serialize methods of the old Mod and old ManagedMods clreplacedes.
// It now uses the new format, but generates an *.xml that is compatible with older versions.
// Since there is now way more information saved: It uses the current disk state, not the pending one. (PreviousMethod, CurrentArchiveName, etc.)
// In case the user wants to downgrade, they can.
XDoreplacedent xmlDoc = new XDoreplacedent();
XElement xmlRoot = new XElement("Mods");
xmlRoot.Add(new XAttribute("doNotImport", true));
xmlDoc.Add(xmlRoot);
xmlDoc.AddFirst(new XComment($"\n This file has been generated by v{Shared.VERSION} for backwards-compatibility.\n It not actually being used anymore.\n"));
foreach (ManagedMod mod in mods)
{
XElement xmlMod = new XElement("Mod",
new XAttribute("replacedle", mod.replacedle),
new XAttribute("enabled", mod.Deployed),
new XAttribute("modFolder", mod.ManagedFolderName),
new XAttribute("installType", GetLegacyInstallMethodName(mod)));
if (mod.URL != "")
xmlMod.Add(new XAttribute("url", mod.URL));
if (mod.Version != "")
xmlMod.Add(new XAttribute("version", mod.Version));
if (mod.PreviousMethod == ManagedMod.DeploymentMethod.SeparateBA2 && mod.CurrentArchiveName != null)
{
xmlMod.Add(new XAttribute("archiveName", mod.CurrentArchiveName));
xmlMod.Add(new XAttribute("compression", GetLegacyArchiveCompressionName(mod)));
xmlMod.Add(new XAttribute("format", GetLegacyArchiveFormatName(mod)));
// We can't set the frozen flag anymore, because we store frozen archives differently now:
//if (mod.Frozen)
//xmlMod.Add(new XAttribute("frozen", mod.Frozen));
}
if (mod.PreviousMethod == ManagedMod.DeploymentMethod.LooseFiles && mod.CurrentRootFolder != "")
xmlMod.Add(new XAttribute("root", mod.CurrentRootFolder));
if (mod.PreviousMethod == ManagedMod.DeploymentMethod.LooseFiles && mod.Deployed)
foreach (String filePath in mod.LooseFiles)
xmlMod.Add(new XElement("File", new XAttribute("path", filePath)));
xmlRoot.Add(xmlMod);
}
xmlDoc.Save(Path.Combine(mods.ModsPath, "manifest.xml"));
}
19
Source : HTMLReportBase.cs
with Apache License 2.0
from Ginger-Automation
with Apache License 2.0
from Ginger-Automation
protected XNode CreateHTMLTable<T>(IEnumerable<T> items, IEnumerable<string> header, params Func<T, string>[] columns)
{
if (!items.Any())
return null;
var html = items.Aggregate(new XElement("table", new XAttribute("border", 1)),
(table, item) =>
{
table.Add(columns.Aggregate(new XElement("tr"),
(row, cell) =>
{
row.Add(new XElement("td", EvalColumn(cell, item)));
return row;
}));
return table;
});
html.AddFirst(header.Aggregate(new XElement("tr"),
(row, caption) => { row.Add(new XElement("th", caption)); return row; }));
return html;
}
19
Source : HTMLReportBase.cs
with Apache License 2.0
from Ginger-Automation
with Apache License 2.0
from Ginger-Automation
protected XNode CreateHTMLTable<T>(IEnumerable<T> items, IEnumerable<string> header, params Func<T, string>[] columns)
{
if (!items.Any())
return null;
var html = items.Aggregate(new XElement("table", new XAttribute("border", 1)),
(table, item) =>
{
table.Add(columns.Aggregate(new XElement("tr"),
(row, cell) =>
{
row.Add(new XElement("td", EvalColumn(cell, item)));
return row;
}));
return table;
});
html.AddFirst(header.Aggregate(new XElement("tr"),
(row, caption) => { row.Add(new XElement("th", caption)); return row; }));
return html;
}
19
Source : SettingsServiceBase.cs
with Mozilla Public License 2.0
from martinstoeckli
with Mozilla Public License 2.0
from martinstoeckli
protected virtual void UpdateSettingsFrom1To2(XElement root)
{
XElement cloudStorageSettings = root.Element("cloud_storage");
if (cloudStorageSettings != null)
{
XElement cloudStorageAccountElement = new XElement("cloud_storage_account");
XElement cloudTypeElement = cloudStorageSettings.Element("cloud_type");
cloudStorageAccountElement.Add(new XElement("cloud_type", cloudTypeElement.Value));
XElement urlElement = cloudStorageSettings.Element("cloud_url");
if (urlElement != null)
cloudStorageAccountElement.Add(new XElement("url", urlElement.Value));
XElement userElement = cloudStorageSettings.Element("cloud_username");
if (userElement != null)
cloudStorageAccountElement.Add(new XElement("username", userElement.Value));
// The attribute "cloud_preplacedword" is protected and can be converted only by a
// platform specific implementation by overriding this method.
root.AddFirst(cloudStorageAccountElement);
}
}
19
Source : SettingsServiceBase.cs
with Mozilla Public License 2.0
from martinstoeckli
with Mozilla Public License 2.0
from martinstoeckli
protected virtual void UpdateSettingsFrom2To3(XElement root)
{
XElement cloudStorageAcount = root.Element("cloud_storage_account");
if (cloudStorageAcount != null)
{
XElement cloudStorageCredentialsElement = new XElement("cloud_storage_credentials");
XElement cloudTypeElement = cloudStorageAcount.Element("cloud_type");
if (cloudTypeElement != null)
cloudStorageCredentialsElement.Add(new XElement("cloud_storage_id", cloudTypeElement.Value.ToLowerInvariant()));
XElement userElement = cloudStorageAcount.Element("username");
if (userElement != null)
cloudStorageCredentialsElement.Add(new XElement("username", EncryptProperty(userElement.Value)));
XElement preplacedwordElement = cloudStorageAcount.Element("protected_preplacedword");
if (preplacedwordElement != null)
{
byte[] preplacedwordBytes = _dataProtectionService.Unprotect(preplacedwordElement.Value);
SecureString preplacedword = SecureStringExtensions.BytesToSecureString(preplacedwordBytes, Encoding.Unicode);
cloudStorageCredentialsElement.Add(new XElement("preplacedword", EncryptProperty(preplacedword.SecureStringToString())));
}
XElement urlElement = cloudStorageAcount.Element("url");
if (urlElement != null)
cloudStorageCredentialsElement.Add(new XElement("url", urlElement.Value));
XElement accessTokenElement = cloudStorageAcount.Element("oauth_access_token");
if (accessTokenElement != null)
cloudStorageCredentialsElement.Add(new XElement("access_token", EncryptProperty(accessTokenElement.Value)));
root.AddFirst(cloudStorageCredentialsElement);
}
}
19
Source : FolderMerger.cs
with MIT License
from michaelscodingspot
with MIT License
from michaelscodingspot
private static XElement MergeFiles(List<string> files)
{
var filesAsXelement = files.Select(file =>
{
var root = XDoreplacedent.Load(file).Root;
root.AddFirst(new XComment(string.Format("Merged from file {0}", Path.GetFileName(file))));
root.AddFirst(new XComment(""));
return root;
});
XElement merged = filesAsXelement.Aggregate((first, second) =>
{
var mergeRes = XamlFileMerger.MergeXamlFiles(first, second);
return mergeRes;
});
merged.AddFirst(new XComment(""));
merged.AddFirst(new XComment("This is an auto-generated file. Do not change by yourself since it's overridden with each build"));
merged.Add(new XComment("This XAML merge infrastructure was provided by http://michaelscodingspot.com/"));
return merged;
}
19
Source : ConvertRDL.cs
with MIT License
from microsoft
with MIT License
from microsoft
private void AlignFilters(XElement reportDataSetElement, XElement currDataSetNode)
{
var currDataSetFilterElements = currDataSetNode.Descendants(currDataSetNode.Name.Namespace + DataSetConstants.Filters);
var reportDataSetFilterElements = reportDataSetElement.Descendants(reportDataSetElement.Name.Namespace + DataSetConstants.Filters);
if (currDataSetFilterElements.Count() != 1)
{
if (currDataSetFilterElements.Count() == 0)
{
return;
}
else
{
throw new Exception("Illegal FIle - " + currDataSetNode.Name.LocalName + " has more than 1 Filters Element found");
}
}
var dataSetFilters = currDataSetFilterElements.First().Elements().ToArray();
XElement reportDataSetFilters;
if (reportDataSetFilterElements.Count() == 0)
{
reportDataSetFilters = new XElement(reportDataSetElement.Name.Namespace + DataSetConstants.Filters);
reportDataSetElement.Add(reportDataSetFilters);
}
else if (reportDataSetFilterElements.Count() == 1)
{
reportDataSetFilters = reportDataSetFilterElements.First();
}
else
{
throw new Exception("Illegal FIle - " + reportDataSetElement.Name.LocalName + " has more than 1 Filters ELement found");
}
for (int i = dataSetFilters.Count() - 1; i >= 0; i--)
{
reportDataSetFilters.AddFirst(dataSetFilters[i]);
}
}
19
Source : SortCommand.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
private void SortSection(XElement parent, XNamespace ns, string key, bool ascending, bool pin)
{
IEnumerable<XElement> sections;
if (ascending)
{
sections = parent.Elements(ns + "Section")
.OrderBy(s => s.Attribute(key).Value)
.ToList();
}
else
{
sections = parent.Elements(ns + "Section")
.OrderByDescending(s => s.Attribute(key).Value)
.ToList();
}
parent.Elements(ns + "Section").Remove();
// Sections must precede any SectionGroups; so use first group as a marker to insert before
var marker = parent.Elements(ns + "SectionGroup").FirstOrDefault();
foreach (var section in sections)
{
if (marker == null)
{
parent.Add(section);
}
else
{
marker.AddBeforeSelf(section);
}
}
if (pin)
{
// move Notes to the beginning
var element = parent.Elements(ns + "Section")
.FirstOrDefault(e => e.Attribute("name").Value == "Notes");
if (element?.PreviousNode != null)
{
element.Remove();
parent.AddFirst(element);
}
// move Quick Notes to the end
element = parent.Elements(ns + "Section")
.FirstOrDefault(e => e.Attribute("name").Value == "Quick Notes");
if (element != null)
{
// regardless of where it is, just remove it and add it back in.
// easier than dealing with case like before/after SectionGroups
element.Remove();
if (marker == null)
{
parent.Add(element);
}
else
{
marker.AddBeforeSelf(element);
}
}
}
var groups = parent.Elements(ns + "SectionGroup")
.Where(e => e.Attribute("isRecycleBin") == null)
.ToList();
foreach (var group in groups)
{
SortSection(group, ns, key, ascending, pin);
}
}
19
Source : FavoritesProvider.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
private static XElement UpgradeFavoritesMenu(XElement root)
{
root = RewriteNamespace(root, ns);
// re-id old add favorite button
var addButton = root.Elements(ns + "button")
.FirstOrDefault(e => e.Attribute("id").Value == "omFavoriteAddButton"); // old id
if (addButton != null)
{
// use new values
addButton.Attribute("id").Value = AddButtonId;
addButton.Attribute("onAction").Value = "AddFavoritePageCmd";
}
else
{
addButton = root.Elements(ns + "button")
.FirstOrDefault(e => e.Attribute("id").Value == AddButtonId);
}
if (addButton == null)
{
addButton = MakeAddButton();
root.AddFirst(addButton);
}
// manage buttons...
var manButton = root.Elements(ns + "button")
.FirstOrDefault(e => e.Attribute("id").Value == ManageButtonId);
if (manButton == null)
{
addButton.AddAfterSelf(MakeManageButton());
}
// convert splitButton to button, removing the delete sub-menu
var elements = root.Elements(ns + "splitButton").ToList();
foreach (var element in elements)
{
var button = element.Elements(ns + "button").First();
button.Attribute("onAction").Value = GotoFavoriteCmd;
element.ReplaceWith(button);
}
return root;
}
19
Source : ExpandoCommand.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
private bool Save()
{
var containers = FindContainers();
if (!containers.Any())
{
return false;
}
foreach (var container in containers)
{
if (container.Attribute("collapsed")?.Value == "1")
{
var meta = container.Elements(ns + "Meta")
.FirstOrDefault(e => e.Attribute("name").Value == MetaName);
if (meta == null)
{
container.AddFirst(new XElement(ns + "Meta",
new XAttribute("name", MetaName),
new XAttribute("content", "1")
));
}
else if (meta.Attribute("content").Value != "1")
{
meta.SetAttributeValue("content", "1");
}
}
else
{
var meta = container.Elements(ns + "Meta")
.FirstOrDefault(e => e.Attribute("name").Value == MetaName);
if (meta != null)
{
// meta.Remove() doesn't work
meta.SetAttributeValue("content", "0");
}
}
}
UIHelper.ShowMessage(Resx.ExpandoCommand_Saved);
return true;
}
19
Source : RemindCommand.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
private bool SetReminder(XElement paragraph, Reminder reminder)
{
var index = page.GetTagDefIndex(reminder.Symbol);
if (index == null)
{
index = page.AddTagDef(reminder.Symbol,
string.Format(Resx.RemindCommand_nameFormat, reminder.Due.ToFriendlyString()));
reminder.TagIndex = index;
}
var tag = paragraph.Elements(ns + "Tag")
.FirstOrDefault(e => e.Attribute("index").Value == index);
if (tag == null)
{
// tags must be ordered by index even within their containing paragraph
// so take all, remove from paragraph, append, sort, re-add...
var tags = paragraph.Elements(ns + "Tag").ToList();
tags.ForEach(t => t.Remove());
// synchronize tag with reminder
var completed = reminder.Status == ReminderStatus.Completed
? "true" : "false";
tag = new XElement(ns + "Tag",
new XAttribute("index", index),
new XAttribute("completed", completed),
new XAttribute("disabled", "false")
);
tags.Add(tag);
paragraph.AddFirst(tags.OrderBy(t => t.Attribute("index").Value));
}
else
{
// synchronize tag with reminder
var tcompleted = tag.Attribute("completed").Value == "true";
var rcompleted = reminder.Status == ReminderStatus.Completed;
if (tcompleted != rcompleted)
{
tag.Attribute("completed").Value = rcompleted ? "true" : "false";
}
}
new ReminderSerializer().StoreReminder(page, reminder);
return true;
}
19
Source : Outline.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
public void SetSize(int width, int height = 0)
{
var size = Element(ns + "Size");
if (size == null)
{
size = new XElement(ns + "Size", new XAttribute("width", $"{width}.0"));
if (height > 0)
{
size.Add(new XAttribute("height", $"{height}.0"));
}
AddFirst(size);
}
else
{
size.SetAttributeValue("width", $"{width}.0");
if (height > 0)
{
size.SetAttributeValue("height", $"{height}.0");
}
}
}
19
Source : Page.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
public void AddQuickStyleDef(XElement def)
{
var tagdef = Root.Elements(Namespace + "TagDef").LastOrDefault();
if (tagdef == null)
{
Root.AddFirst(def);
}
else
{
tagdef.AddAfterSelf(def);
}
}
19
Source : Page.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
public string AddTagDef(string symbol, string name, int tagType = 0)
{
var tags = Root.Elements(Namespace + "TagDef");
int index = 0;
if (tags?.Any() == true)
{
var tag = tags.FirstOrDefault(e => e.Attribute("symbol").Value == symbol);
if (tag != null)
{
return tag.Attribute("index").Value;
}
index = tags.Max(e => int.Parse(e.Attribute("index").Value)) + 1;
}
Root.AddFirst(new XElement(Namespace + "TagDef",
new XAttribute("index", index.ToString()),
new XAttribute("type", tagType.ToString()),
new XAttribute("symbol", symbol),
new XAttribute("fontColor", "automatic"),
new XAttribute("highlightColor", "none"),
new XAttribute("name", name)
));
return index.ToString();
}
19
Source : Page.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
public XElement EnsureContentContainer()
{
XElement container;
var outline = Root.Elements(Namespace + "Outline").LastOrDefault();
if (outline == null)
{
container = new XElement(Namespace + "OEChildren");
outline = new XElement(Namespace + "Outline", container);
Root.Add(outline);
}
else
{
container = outline.Elements(Namespace + "OEChildren").LastOrDefault();
if (container == null)
{
container = new XElement(Namespace + "OEChildren");
outline.Add(container);
}
}
// check Outline size
var size = outline.Elements(Namespace + "Size").FirstOrDefault();
if (size == null)
{
// this size is close to OneNote defaults when a new Outline is created
outline.AddFirst(new XElement(Namespace + "Size",
new XAttribute("width", "300.0"),
new XAttribute("height", "14.0")
));
}
return container;
}
19
Source : Page.cs
with Mozilla Public License 2.0
from stevencohn
with Mozilla Public License 2.0
from stevencohn
public void SetMeta(string name, string value)
{
var meta = Root.Elements(Namespace + "Meta")
.FirstOrDefault(e => e.Attribute("name").Value == name);
if (meta == null)
{
meta = new XElement(Namespace + "Meta",
new XAttribute("name", name),
new XAttribute("content", value)
);
// add into schema sequence...
var after = Root.Elements(Namespace + "QuickStyleDef").LastOrDefault();
if (after == null)
{
after = Root.Elements(Namespace + "TagDef").LastOrDefault();
}
if (after == null)
{
Root.AddFirst(meta);
}
else
{
after.AddAfterSelf(meta);
}
}
else
{
meta.Attribute("content").Value = value;
}
}
19
Source : Patch.cs
with GNU General Public License v3.0
from uholeschak
with GNU General Public License v3.0
from uholeschak
public static void UpdateConfigNode(XElement settingsNode, string key, string value, bool onlyExisting = false)
{
XElement node = (from addNode in settingsNode.Elements("add")
let keyAttrib = addNode.Attribute("key")
where keyAttrib != null
where string.Compare(keyAttrib.Value, key, StringComparison.OrdinalIgnoreCase) == 0
select addNode).FirstOrDefault();
if (node == null)
{
if (onlyExisting)
{
return;
}
node = new XElement("add");
node.Add(new XAttribute("key", key));
settingsNode.AddFirst(node);
}
XAttribute valueAttrib = node.Attribute("value");
if (valueAttrib == null)
{
valueAttrib = new XAttribute("value", value);
node.Add(valueAttrib);
}
else
{
valueAttrib.Value = value;
}
}
19
Source : OneNotePageProxy.cs
with Microsoft Public License
from WetHat
with Microsoft Public License
from WetHat
private bool ApplyTagsToPage() {
if (_tags == null) {
return false; // can only apply tags once
}
bool specChanged = UpdateTagSpec();
// get the new set of tags
string newMetaContent = _meta != null ? _meta.Attribute("content").Value : String.Empty;
XName tagName = _one.GetName("Tag");
if (string.IsNullOrEmpty(newMetaContent)) {
if (_pageTagsOE != null) { // no more tags - remove tag display
if (_pageTagsOE == _replacedleOE) { // in replacedle tag
string markertagindex = _markerTagDef.Attribute("index").Value;
XElement markerTag = _replacedleOE.Elements(tagName).FirstOrDefault(t => t.Attribute("index").Value == markertagindex);
markerTag.Remove();
} else { // below replacedle tags
_onenote.DeletePageContent(PageID, _pageTagsOE.Parent.Parent.Attribute("objectID").Value);
_pageTagsOE.Parent.Parent.Remove();
_pageTagsOE = null;
}
}
return true;
}
if (_pageTagsOE == null) { // make sure we update the page even if tags are unchanged
specChanged = true;
}
XName tagdefName = _one.GetName("TagDef");
if (specChanged) { // some differences detected - must update
string markerTagIndex = _markerTagDef.Attribute("index").Value; ;
switch ((TagDisplay)Properties.Settings.Default.TagDisplay) {
case TagDisplay.Belowreplacedle:
// remove unwanted representation - in replacedle tags
if (_pageTagsOE != null && _pageTagsOE == _replacedleOE) {
XElement tag = _pageTagsOE.Elements(tagName).FirstOrDefault(e => e.Attribute("index").Value == markerTagIndex);
if (tag != null) {
tag.Remove();
}
_pageTagsOE = null; // rebuild outline;
}
// update/create the tag outline
if (_pageTagsOE != null) { // remove all old <one:T> text elements, but leave the marker tag in place.
XName tName = _one.GetName("T");
foreach (XElement t in _pageTagsOE.Elements(tName).ToArray()) {
t.Remove();
}
// Add comma separated tags
_pageTagsOE.Add(new XElement(tName, newMetaContent));
} else { // build new outline for the tags
// Create a style for the tags - if needed
// <one:QuickStyleDef index="1"
// name="cite" fontColor="#595959" highlightColor="automatic"
// font="Calibri" fontSize="9"
XName styledefName = _one.GetName("QuickStyleDef");
IEnumerable<XElement> quickstyleDefs = _page.Elements(styledefName);
XElement tagStyle = quickstyleDefs.FirstOrDefault(d => d.Attribute("name").Value == Properties.Settings.Default.TagOutlineStyle_Name);
if (tagStyle == null) { // new style required
tagStyle = new XElement(styledefName,
new XAttribute("index", (quickstyleDefs.Count() + 1).ToString()),
new XAttribute("name", Properties.Settings.Default.TagOutlineStyle_Name),
new XAttribute("fontColor", "#595959"),
new XAttribute("highlightColor", "automatic"),
new XAttribute("bold", Properties.Settings.Default.TagOutlineStyle_Font.Bold.ToString().ToLower()),
new XAttribute("italic", Properties.Settings.Default.TagOutlineStyle_Font.Italic.ToString().ToLower()),
new XAttribute("font", Properties.Settings.Default.TagOutlineStyle_Font.Name),
new XAttribute("fontSize", Properties.Settings.Default.TagOutlineStyle_Font.Size));
addElementToPage(tagStyle, QUICKSTYLEDEF_IDX);
}
// create a tag outline
// Create an outline for the page tags
//
//<one:Outline author="Peter Ernst" authorInitials="PE" lastModifiedBy="Peter Ernst" lastModifiedByInitials="PE" objectID="{E470786C-A904-4E9F-AC3B-0D9F36B6FC54}{14}{B0}" lastModifiedTime="2013-12-06T16:04:48.000Z">
// <one:Position x="236.249984741211" y="42.1500015258789" z="0" />
// <one:Size width="90.8847274780273" height="10.9862976074219" />
// <one:OEChildren>
// <one:OE objectID="{E470786C-A904-4E9F-AC3B-0D9F36B6FC54}{15}{B0}" lastModifiedTime="2013-12-06T16:04:48.000Z" quickStyleIndex="1" creationTime="2013-12-06T16:03:50.000Z">
// <one:Tag index="0" completed="true" creationDate="2013-12-06T15:55:59.000Z" completionDate="2013-12-06T15:55:59.000Z" />
// <one:T><![CDATA[Gdfgdf, sdfdsf]]></one:T>
// </one:OE>
// </one:OEChildren>
//</one:Outline>
XElement outline = new XElement(_one.GetName("Outline"),
new XElement(_one.GetName("Position"),
new XAttribute("x", "236"),
new XAttribute("y", "43"),
new XAttribute("z", "0")),
new XElement(_one.GetName("Size"),
new XAttribute("width", "400"),
new XAttribute("height", "10"),
new XAttribute("isSetByUser", "true")),
new XElement(_one.GetName("OEChildren"),
(_pageTagsOE = new XElement(_one.GetName("OE"),
new XAttribute("quickStyleIndex", tagStyle.Attribute("index").Value),
new XElement(tagName,
new XAttribute("index", _markerTagDef.Attribute("index").Value),
new XAttribute("completed", "true")),
new XElement(_one.GetName("T"), newMetaContent)))));
_page.Add(outline);
}
// turn off spell checking
_pageTagsOE.SetAttributeValue("lang", "yo");
break;
case TagDisplay.Inreplacedle:
if (_pageTagsOE != null && _pageTagsOE != _replacedleOE) { // remove unwanted representation - below replacedle tags
_onenote.DeletePageContent(PageID, _pageTagsOE.Parent.Parent.Attribute("objectID").Value);
_pageTagsOE.Parent.Parent.Remove();
_pageTagsOE = _replacedleOE;
}
// tag the replacedle if needed
if (_replacedleOE.Elements(tagName).FirstOrDefault(e => markerTagIndex.Equals(e.Attribute("index").Value)) == null) {
_replacedleOE.AddFirst(new XElement(tagName,
new XAttribute("index", markerTagIndex),
new XAttribute("completed", "true")));
}
break;
}
}
return specChanged;
}
19
Source : OneNotePageProxy.cs
with Microsoft Public License
from WetHat
with Microsoft Public License
from WetHat
private bool UpdateTagSpec() {
bool specChanged = false;
// collect all tag definitions
XName tagdefName = _one.GetName("TagDef");
IEnumerable<XElement> tagDefs = _page.Elements(tagdefName);
int nextTagDefIndex = tagDefs.Count(); // next index for creating new tags
// add new tags to the page replacedle and remove obsolete ones
// <one:replacedle lang="de">
// <one:OE objectID="{9A0ACA13-6D63-4137-8821-5D7C5408BB6C}{15}{B0}" lastModifiedTime="2013-12-08T14:08:11.000Z" quickStyleIndex="0" author="Peter Ernst" authorInitials="PE" lastModifiedBy="Peter Ernst" lastModifiedByInitials="PE" creationTime="2013-12-08T14:08:11.000Z">
// <one:Tag index="0" completed="true" creationDate="2013-12-06T20:31:43.000Z" completionDate="2013-12-06T20:31:43.000Z" />
// <one:Tag index="1" completed="true" creationDate="2013-12-06T20:34:05.000Z" completionDate="2013-12-06T20:34:05.000Z" />
// <one:Tag index="2" completed="true" creationDate="2013-12-06T20:35:41.000Z" completionDate="2013-12-06T20:35:41.000Z" />
// <one:T><![CDATA[Test Addin ]]></one:T>
// </one:OE>
//</one:replacedle>
// Locate tag definitions for existing page tags and record them:
// <one:TagDef index="0" name="Test Tag 1" type="0" symbol="0" />
// <one:TagDef index="1" name="Test Tag 2" type="1" symbol="0" />
var tagnameToTagdefMap = new Dictionary<string, XElement>();
int redundantTagCount = 0;
foreach (XElement tagdef in tagDefs.Where(d => d.Attribute("symbol").Value == "0"
&& _originalTags.Contains(d.Attribute("name").Value))) {
string tagname = tagdef.Attribute("name").Value;
if (tagnameToTagdefMap.ContainsKey(tagname)) { // another tag with that name already exists.
// Give that tag a unique
// name, so that if can be
// cleaned up later
tagname = string.Format("{0}@#|{1}", tagname, redundantTagCount++);
}
tagnameToTagdefMap[tagname] = tagdef;
// make sure type is equal to index so that type is unique
tagdef.Attribute("type").Value = tagdef.Attribute("index").Value;
// remove any color attribute so that the replacedle can show its original color
if (tagdef.Attribute("fontColor") != null) {
tagdef.Attribute("fontColor").Remove();
}
}
XName tagName = _one.GetName("Tag");
// add new tag definitions, if needed
foreach (string tag in PageTags) {
XElement tagdef;
string strIndex;
if (tagnameToTagdefMap.TryGetValue(tag, out tagdef)) {
strIndex = tagdef.Attribute("index").Value;
} else { // create a new definition for this tag
strIndex = (nextTagDefIndex++).ToString(CultureInfo.InvariantCulture);
tagdef = new XElement(tagdefName, new XAttribute("index", strIndex),
new XAttribute("name", tag),
new XAttribute("type", strIndex),
new XAttribute("symbol", "0"));
_page.AddFirst(tagdef);
}
// tag the replacedle with an invisible tag if needed
XElement replacedleTag = _replacedleOE.Elements(tagName).FirstOrDefault(t => t.Attribute("index").Value == strIndex);
if (replacedleTag == null) {
_replacedleOE.AddFirst(new XElement(tagName,
new XAttribute("index", strIndex),
new XAttribute("completed", "true")));
specChanged = true;
}
tagnameToTagdefMap.Remove(tag); // remove used tag
}
// remove unused tags from the replacedle; this also automatically removes their
// definitions on next page update.
// TODO: avoid quadratic lookup
foreach (XElement td in tagnameToTagdefMap.Values) {
string strIndex = td.Attribute("index").Value;
XElement tag = _replacedleOE.Elements(tagName).FirstOrDefault(t => t.Attribute("index").Value == strIndex);
if (tag != null) {
tag.Remove();
specChanged = true;
}
}
string strTags = string.Join(", ", PageTags);
// create the <one:Meta> element for page tags, if needed
if (_tags.Length > 0) { // we have tags to set
if (_meta == null) {
_meta = new XElement(_one.GetName("Meta"),
new XAttribute("name", META_NAME));
addElementToPage(_meta, META_IDX);
specChanged = true;
}
_meta.SetAttributeValue("content", strTags);
} else {
if (_meta != null) { // we cannot remove the meta element, so we just set it to the empty string.
_meta.SetAttributeValue("content", string.Empty);
specChanged = true;
}
}
// create or update the marker tag definition
if (_markerTagDef != null) { // existing tag definition recycling
switch ((TagDisplay)Properties.Settings.Default.TagDisplay) {
case TagDisplay.Belowreplacedle:
if (!"23".Equals(_markerTagDef.Attribute("type").Value)) {
_markerTagDef.SetAttributeValue("type", "23");
specChanged = true;
}
if (!MarkerTagname.Equals(_markerTagDef.Attribute("type").Name)) {
_markerTagDef.SetAttributeValue("name", MarkerTagname);
specChanged = true;
}
break;
case TagDisplay.Inreplacedle:
if (!"99".Equals(_markerTagDef.Attribute("type").Value)) {
_markerTagDef.SetAttributeValue("type", "99");
specChanged = true;
}
if (!strTags.Equals(_markerTagDef.Attribute("name").Value)) {
_markerTagDef.SetAttributeValue("name", strTags);
specChanged = true;
}
break;
}
} else { // create a new tag definition
string strIndex = nextTagDefIndex.ToString(CultureInfo.InvariantCulture);
switch ((TagDisplay)Properties.Settings.Default.TagDisplay) {
case TagDisplay.Belowreplacedle:
_markerTagDef = new XElement(tagdefName,
new XAttribute("index", strIndex),
new XAttribute("symbol", "26"),
new XAttribute("name", MarkerTagname),
new XAttribute("type", "23"));
break;
case TagDisplay.Inreplacedle:
_markerTagDef = new XElement(tagdefName,
new XAttribute("index", strIndex),
new XAttribute("symbol", "26"),
new XAttribute("name", strTags),
new XAttribute("type", "99"));
break;
}
_page.AddFirst(_markerTagDef);
specChanged = true;
}
return specChanged;
}
19
Source : CSharpLatest.cs
with BSD 2-Clause "Simplified" License
from zoon
with BSD 2-Clause "Simplified" License
from zoon
private static bool ChangeOrSetProperty(XContainer root, XNamespace ns, string name, string val)
{
XElement node = root.Elements(ns + "PropertyGroup").Elements(ns + name).FirstOrDefault()
?? new XElement(ns + name, "?");
if (node.Value == val) return false;
node.Value = val;
if (node.Parent == null)
{
var propertyGroup = new XElement(ns + "PropertyGroup");
root.AddFirst(propertyGroup);
propertyGroup.Add(node);
}
return true;
}