System.Xml.Linq.XElement.Attribute(System.Xml.Linq.XName)

Here are the examples of the csharp api System.Xml.Linq.XElement.Attribute(System.Xml.Linq.XName) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1283 Examples 7

19 Source : CheckCreateFile.cs
with MIT License
from 3RD-Dimension

public static void CheckAndUpdateXMLFile(int CurrentKeyFileVersion)
        {
            MainWindow.Logger.Info($"Updating HotkeyXML File. Current File Version {CurrentKeyFileVersion}, Update to File Version {HotKeyFileVer}");
            // Define new Hotkey fields - This changes every program update if needed   
            var UpdateHotkey = XDoreplacedent.Load(HotKeyFile);

            // NOTES | Sample Code for Add, Add at position, Rename:
            // Add to end of file: xDoc.Root.Add(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Add to specific Location: xDoc.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Rename Hotkey Data
            //var hotKeyRename1 = xDoc.Descendants("bind").Where(arg => arg.Attribute("key_description").Value == "Feed Rate Increase").Single();
            //hotKeyRename1.Attribute("key_description").Value = "Feed Rate Increase X";

            // START FILE MANIPULATION
            // Insert at specific Location - Reverse Order - Bottom will be inserted at the top
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Z"), new XAttribute("keyfunction", "JDistDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Z"), new XAttribute("keyfunction", "JDistIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Y"), new XAttribute("keyfunction", "JDistDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Y"), new XAttribute("keyfunction", "JDistIncY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease X"), new XAttribute("keyfunction", "JDistDecX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase X"), new XAttribute("keyfunction", "JDistIncX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Z"), new XAttribute("keyfunction", "JRateDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Z"), new XAttribute("keyfunction", "JRateIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Y"), new XAttribute("keyfunction", "JRateDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Y"), new XAttribute("keyfunction", "JRateIncY"), new XAttribute("keycode", "")));

            // Change Hotkey Desciptions and Keyfunction Name
            var hotKeyRename1 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateInc").Single();
            var hotKeyRename2 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateDec").Single();
            hotKeyRename1.Attribute("key_description").Value = "Jog Rate Increase X";
            hotKeyRename1.Attribute("keyfunction").Value = "JRateIncX";
            hotKeyRename2.Attribute("key_description").Value = "Jog Rate Decrease X";
            hotKeyRename2.Attribute("keyfunction").Value = "JRateDecX";

            // END FILE MANIPULATION
            UpdateHotkey.Root.Attribute("HotkeyFileVer").Value = HotKeyFileVer.ToString(); // Change HotkeyFileVer to current version

            //And save the XML file
            UpdateHotkey.Save(HotKeyFile);

            // Re-load Hotkeys
            HotKeys.LoadHotKeys();
        }

19 Source : SuppressionFileIOTests.cs
with GNU General Public License v3.0
from Acumatica

[Fact]
		public void CheckSuppressionMessageConversion_FromXml()
		{
			var xElement = GetXElementsToCheck().Take(1).Single();
			var target = xElement.Element("target").Value;
			var syntaxNode = xElement.Element("syntaxNode").Value;

			var messageToCheck = SuppressMessage.MessageFromElement(xElement);

			messageToCheck.Should().NotBeNull();
			messageToCheck.Value.Id.Should().Be(xElement.Attribute("id").Value);
			messageToCheck.Value.Target.Should().Be(target);
			messageToCheck.Value.SyntaxNode.Should().Be(syntaxNode);
		}

19 Source : SuppressMessage.cs
with GNU General Public License v3.0
from Acumatica

public static SuppressMessage? MessageFromElement(XElement element)
		{
			string id = element?.Attribute(IdAttribute)?.Value;
			if (id.IsNullOrWhiteSpace())
				return null;

			string target = element.Element(TargetElement)?.Value;
			if (target.IsNullOrWhiteSpace())
				return null;

			string syntaxNode = element.Element(SyntaxNodeElement)?.Value;
			if (syntaxNode.IsNullOrWhiteSpace())
				return null;

			return new SuppressMessage(id, target, syntaxNode);
		}

19 Source : ProcessNuPropsTask.cs
with MIT License
from adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (SourceFiles == null)
            {
                Log.LogMessage("No source code available");
                return true; //nothing to process
            }

            //process the source files
            var anyPackageAvailable = false;
            foreach (var sourceFile in SourceFiles)
            {
                var fileNameFull = sourceFile.GetMetadata("FullPath");
                var fileName = new FileInfo(fileNameFull).Name;

                //Get the NuProps from XML Doreplacedentation Comments <NuProp.xxxx>
                var sourceContent = File.ReadAllText(fileNameFull);
                var sourceLines = sourceContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                //Extract all comments
                var stringBuilder = new StringBuilder();
                foreach (var contentLine in sourceLines)
                {
                    var sourceLine = contentLine.Trim();
                    if (sourceLine.StartsWith("///"))
                    {
                        stringBuilder.AppendLine(sourceLine.Substring(3));
                    }
                }

                //Get all comments in single XML - encapsulate the whole bunch with dummy tag "doc" allowing the XDoreplacedent to parse it
                var xDoreplacedent = XDoreplacedent.Parse("<doc>" + stringBuilder + "</doc>");
                //Get NuProp comments
                var nuPropElements = xDoreplacedent.Descendants()
                    .Where(n => n is XElement e && e.Name.LocalName.StartsWith("NuProp.")).ToList();

                if (nuPropElements.Count <= 0) continue; //no NuProps - continue with the next file

                //Has some NuProp -> process
                //<NuProp.Id></NuProp.Id> - package ID (mandatory)
                //<NuProp.Version></NuProp.Version>   - package version base (major.minor.patch) - optional          
                //<NuProp.Description></NuProp.Description> - package description (optional)
                //<NuProp.Tags></NuProp.Tags> - package tags (optional)
                //<NuProp.Using id = "" version=""/> - package imports (optional). Version is optional
                //<NuProp.Needs id="" /> - "external" imports needed (optional) - not included in package, just info when consuming!!!

                var nuPropId = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Id")?.Value.Trim();
                var nuPropVersion = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Version")?.Value.Trim();
                var nuPropDescription = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Description")?.Value.Trim();
                var nuPropTags = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Tags")?.Value.Trim();

                var nuPropsIncludes = IncludesEnum.None;
                var nuPropIncludesStr = nuPropElements
                    .FirstOrDefault(e => e.Name.LocalName == "NuProp.Includes" && e.Attribute("type")?.Value != null)?
                    .Attribute("type")?.Value;
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (nuPropIncludesStr)
                {
                    case "Folder": nuPropsIncludes = IncludesEnum.Folder; break;
                    case "FolderRecursive": nuPropsIncludes = IncludesEnum.FolderRecursive; break;
                }

                var nuPropUsings = nuPropElements.Where(e => e.Name.LocalName == "NuProp.Using" && e.Attribute("id")?.Value != null).ToList();

                if (string.IsNullOrEmpty(nuPropId))
                {
                    Log.LogWarning($"NuProp.Id not found for {fileName}");
                    continue;
                }

                //Build the partial NuSpec file
                anyPackageAvailable = true;
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = fileNameFull + ".partnuspec";
                var outXDoc = File.Exists(outFile) ? XDoreplacedent.Load(outFile) : new XDoreplacedent();
                var outXDocStrOriginal = outXDoc.ToString();
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                SetOrCreateElement(metadataXElement, "id", ns, nuPropId);
                SetOrCreateElement(metadataXElement, "version", ns, nuPropVersion, false); //don't create if the nuPropVersion is empty/not set
                SetOrCreateElement(metadataXElement, "description", ns, nuPropDescription, false); //don't create if the nuPropDescription is empty/not set
                SetOrCreateElement(metadataXElement, "tags", ns, nuPropTags, false); //don't create if the nuPropTags is empty/not set

                GetEmptyOrCreateElement(metadataXElement, "contentFiles", ns)
                    .Add(new XElement(ns + "files", //<files include="cs/**/*.*" buildAction="Compile" />
                        new XAttribute("include", "cs/**/*.*"),
                        new XAttribute("buildAction", "Compile")));


                //Dependencies
                var dependenciesXElement = GetEmptyOrCreateElement(metadataXElement, "dependencies", ns);
                if (nuPropUsings.Count > 0)
                {
                    //have some dependencies
                    foreach (var nuPropUsing in nuPropUsings)
                    {
                        // ReSharper disable once PossibleNullReferenceException - should not be null based on Where clause for nuPropUsings
                        var depId = nuPropUsing.Attribute("id").Value;
                        var depVersion = nuPropUsing.Attribute("version")?.Value;
                        var dependencyXElement = new XElement(ns + "dependency", new XAttribute("id", depId), new XAttribute("include", "all"));
                        if (string.IsNullOrEmpty(depVersion)) depVersion = "%%CURRENT_VERSION%%";
                        dependencyXElement.Add(new XAttribute("version", depVersion));
                        dependenciesXElement.Add(dependencyXElement);
                    }
                }
                else
                {
                    //Clean dependencies
                    dependenciesXElement.Remove();
                }

                //<files>
                //    < file src = "src.cs" target = "content\App_Packages\pkg_id\src.cs" />
                //    < file src = "src.cs" target = "contentFiles\cs\any\App_Packages\pkg_id\src.cs" />
                //</ files >
                var files = GetEmptyOrCreateElement(packageXElement, "files", ns);
                files.Add(
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{fileName}")),
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{fileName}")));

                if (nuPropsIncludes != IncludesEnum.None)
                {
                    var mainItemDir = sourceFile.GetMetadata("RootDir") + sourceFile.GetMetadata("Directory");
                    Log.LogMessage($"MainItemDir:{mainItemDir}");
                    IEnumerable<ITaskItem> itemsToAdd;
                    switch (nuPropsIncludes)
                    {
                        case IncludesEnum.Folder:
                            itemsToAdd = SourceFiles.Where(itm =>
                                itm.GetMetadata("RootDir") + itm.GetMetadata("Directory") == mainItemDir &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        case IncludesEnum.FolderRecursive:
                            itemsToAdd = SourceFiles.Where(itm =>
                                (itm.GetMetadata("RootDir") + itm.GetMetadata("Directory")).StartsWith(mainItemDir) &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }

                    foreach (var item in itemsToAdd)
                    {
                        var itemFileFull = item.GetMetadata("FullPath");
                        Log.LogMessage($"itemFileFull:{itemFileFull}");
                        var itemFileRel = itemFileFull.Substring(mainItemDir.Length);
                        files.Add(
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{itemFileRel}")),
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{itemFileRel}")));
                    }
                }

                var outXDocStrNew = outXDoc.ToString();
                if (outXDocStrNew == outXDocStrOriginal) continue;

                //change - > save
                File.WriteAllText(outFile, outXDocStrNew);
                Log.LogMessage($"Generated/updated {outFile}");
            }

            if (!anyPackageAvailable)
            {
                Log.LogMessage("No source-only packages found");
            }
            return true;
        }

19 Source : RealXamlPacakge.cs
with MIT License
from admaiorastudio

public int OnAfterSave(uint docCookie)
        {
            if (!UpdateManager.Current.IsConnected)
            {
                System.Diagnostics.Debug.WriteLine("RealXaml was unable to send the xaml. No connection to the notifier.");
                return VSConstants.S_OK;
            }

            ThreadHelper.ThrowIfNotOnUIThread();

            if (_dte == null)
                return VSConstants.S_OK;

            try
            {
                Doreplacedent doc = FindDoreplacedentByCookie(docCookie);
                if (doc == null)
                    return VSConstants.S_OK;

                string kind = doc.Kind;
                string lang = doc.Language;

                string filePath = doc.FullName;
                string fileExt = Path.GetExtension(filePath)?.ToLower() ?? ".unknown";
                if (fileExt != ".xaml")
                    return VSConstants.S_OK;

                XDoreplacedent xdoc = XDoreplacedent.Load(filePath);
                XNamespace xnsp = "http://schemas.microsoft.com/winfx/2009/xaml";
                string pageId = xdoc.Root.Attribute(xnsp + "Clreplaced").Value;

                TextDoreplacedent textdoc = (TextDoreplacedent)(doc.Object("TextDoreplacedent"));
                var p = textdoc.StartPoint.CreateEditPoint();
                string xaml = p.GetText(textdoc.EndPoint);

                _xamlCache[pageId] = xaml;

                // Save is due to a project build
                // Xaml will be sent after the build
                if (!this.IsBuilding)
                {
                    Task.Run(
                        async () =>
                        {
                            try
                            {
                                await UpdateManager.Current.SendXamlAsync(pageId, xaml, true);
                            }
                            catch (Exception ex)
                            {
                                _outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
                                _outputPane.OutputString(Environment.NewLine);
                                _outputPane.OutputString(ex.ToString());
                                _outputPane.OutputString(Environment.NewLine);

                                System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
                                System.Diagnostics.Debug.WriteLine(ex);

                            }
                        });
                }
            }
            catch (Exception ex)
            {
                _outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
                _outputPane.OutputString(Environment.NewLine);
                _outputPane.OutputString(ex.ToString());
                _outputPane.OutputString(Environment.NewLine);

                System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return VSConstants.S_OK;
        }

19 Source : RealXamlPacakge.cs
with MIT License
from admaiorastudio

private async void UpdateManager_PageAppeared(object sender, PageNotificationEventArgs e)
        {
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
            _outputPane.OutputString($"The page '{e.PageId}' is now visible.");
            _outputPane.OutputString(Environment.NewLine);

            System.Diagnostics.Debug.WriteLine($"The page '{e.PageId}' is now visible.");

            try
            {
                EnvDTE.Projecreplacedem appPi = _dte.Solution.FindProjecreplacedem("App.xaml");
                if (appPi != null)
                {
                    foreach (Projecreplacedem pi in appPi.ContainingProject.Projecreplacedems)
                    {
                        if (!pi.Name.Contains(".xaml"))
                            continue;

                        string fileName = pi.FileNames[0];
                        XDoreplacedent xdoc = XDoreplacedent.Load(fileName);
                        XNamespace xnsp = "http://schemas.microsoft.com/winfx/2009/xaml";
                        string pageId = xdoc.Root.Attribute(xnsp + "Clreplaced").Value;
                        if (pageId != e.PageId)
                            continue;

                        var doreplacedent = pi.Doreplacedent;
                        string localPath = pi.Properties.Item("LocalPath").Value?.ToString();
                        string xaml = System.IO.File.ReadAllText(localPath);

                        await UpdateManager.Current.SendXamlAsync(pageId, xaml, false);
                    }
                }
            }
            catch(Exception ex)
            {
                _outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
                _outputPane.OutputString(Environment.NewLine);
                _outputPane.OutputString(ex.ToString());
                _outputPane.OutputString(Environment.NewLine);

                System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

19 Source : EnumerableExtensions.cs
with MIT License
from Adoxio

private static void AddColumnsBasedOnSavedQuery(DataTable table, Enreplacedy savedQuery)
		{
			if (savedQuery == null)
			{
				return;
			}

			var layoutXml = XElement.Parse(savedQuery.GetAttributeValue<string>("layoutxml"));

			var layoutRow = layoutXml.Element("row");

			if (layoutRow == null)
			{
				return;
			}

			var cellNames = layoutRow.Elements("cell").Select(cell => cell.Attribute("name")).Where(name => name != null);

			foreach (var name in cellNames)
			{
				table.Columns.Add(name.Value);
			}
		}

19 Source : FetchXml.cs
with MIT License
from Adoxio

private static bool TryGetFirstAttribute(XNode xml, string xpath, XName attributeName, out string attributeValue)
		{
			attributeValue = null;

			var element = xml.XPathSelectElements(xpath).FirstOrDefault();

			if (element == null)
			{
				return false;
			}

			var attribute = element.Attribute(attributeName);

			if (attribute == null)
			{
				return false;
			}

			attributeValue = attribute.Value;

			return !string.IsNullOrEmpty(attributeValue);
		}

19 Source : FetchXml.cs
with MIT License
from Adoxio

public static string GetAttributeValue(this XElement element, XName name)
		{
			return element != null ? element.Attribute(name).GetValue() : null;
		}

19 Source : Extensions.cs
with MIT License
from Adoxio

public static T? GetAttribute<T>(this XElement element, XName name, IDictionary<T, string> lookup) where T : struct
		{
			var attribute = element.Attribute(name);

			if (attribute != null)
			{
				var value = lookup.First(pair => pair.Value == attribute.Value);

				return value.Key;
			}

			return null;
		}

19 Source : Extensions.cs
with MIT License
from Adoxio

public static T? GetAttribute<T>(this XElement element, XName name, Func<string, T> GetKeyByValue) where T : struct
        {
            var attribute = element.Attribute(name);

            if (attribute != null)
            {
                return GetKeyByValue(attribute.Value);
            }

            return null;
        }

19 Source : ExtendedAttributeSearchResultInfo.cs
with MIT License
from Adoxio

public IDictionary<string, string> GetAttributes(Enreplacedy enreplacedy, IDictionary<string, EnreplacedyMetadata> metadataCache)
		{
			if (AttributeLayoutXml == null || enreplacedy == null)
			{
				return CreateBaseAttributesDictionary();
			}

			var attributeLookup = Metadata.Attributes.ToDictionary(a => a.LogicalName, a => a);

			var attributes = CreateBaseAttributesDictionary();

			var names = from cell in AttributeLayoutXml.XPathSelectElements("//cell")
				select cell.Attribute("name")
				into nameAttibute where nameAttibute != null
				select nameAttibute.Value
				into name where !string.IsNullOrEmpty(name)
				select name;

			foreach (var name in names)
			{
				AttributeMetadata attributeMetadata;

				if (!attributeLookup.TryGetValue(name, out attributeMetadata))
				{
					continue;
				}

				var resultAttribute = GetSearchResultAttribute(Context, enreplacedy, attributeMetadata, metadataCache);

				if (resultAttribute == null)
				{
					continue;
				}

				attributes[resultAttribute.Value.Key] = resultAttribute.Value.Value;
			}

			return attributes;
		}

19 Source : CrmChart.cs
with MIT License
from Adoxio

private void ReplacePresentationDescriptionOptionSetPlaceholders(XElement element, string attributeName, OrganizationServiceContext serviceContext)
		{
			var attribute = element.Attribute(attributeName);

			if (attribute == null)
			{
				return;
			}

			var placeholderMatch = OptionSetPatternRegex.Match(attribute.Value);

			if (placeholderMatch.Success)
			{
				attribute.SetValue(this.ReplacePresentationDescriptionOptionSetPlaceholderMatch(placeholderMatch, serviceContext));
			}
		}

19 Source : Order.cs
with MIT License
from Adoxio

public static Order Parse(XElement element)
		{
			if (element == null) return null;

			var attribute = element.Attribute("descending");

			bool descending;

			var direction = attribute != null && bool.TryParse(attribute.Value, out descending)
				? descending ? OrderType.Descending : OrderType.Ascending as OrderType?
				: null;

			return new Order
			{
				Attribute = element.GetAttribute("attribute"),
				Alias = element.GetAttribute("alias"),
				Direction = direction,

				Extensions = element.GetExtensions(),
			};
		}

19 Source : Extensions.cs
with MIT License
from Adoxio

public static string GetAttribute(this XElement element, XName name)
		{
			var attribute = element.Attribute(name);
			return attribute != null ? attribute.Value : null;
		}

19 Source : Extensions.cs
with MIT License
from Adoxio

public static T GetAttribute<T>(this XElement element, XName name)
		{
			var attribute = element.Attribute(name);
			var value = GetAttribute<T>(attribute);
			return value != null ? (T)value : default(T);
		}

19 Source : TabTemplate.cs
with MIT License
from Adoxio

public override void InstantiateIn(Control container)
		{
			var tabTable = new HtmlGenericControl("div");

			string tabName;
			var tabLabel = string.Empty;
			var tabCssClreplacedName = string.Empty;

			if (Node.TryGetAttributeValue(".", "name", out tabName))
			{
				tabTable.Attributes.Add("data-name", tabName);

				if (_webformMetadata != null)
				{
					var tabWebFormMetadata = _webformMetadata.FirstOrDefault(wfm => wfm.GetAttributeValue<string>("adx_tabname") == tabName);

					if (tabWebFormMetadata != null)
					{
						var label = tabWebFormMetadata.GetAttributeValue<string>("adx_label");

						if (!string.IsNullOrWhiteSpace(label))
						{
							tabLabel = Localization.GetLocalizedString(label, LanguageCode);
						}

						tabCssClreplacedName = tabWebFormMetadata.GetAttributeValue<string>("adx_cssclreplaced") ?? string.Empty;
					}
				}
			}

			tabTable.Attributes.Add("clreplaced", !string.IsNullOrWhiteSpace(tabCssClreplacedName) ? string.Join(" ", "tab clearfix", tabCssClreplacedName) : "tab clearfix");

			if (ShowLabel)
			{
				var caption = new HtmlGenericControl("h2") { InnerHtml = string.IsNullOrWhiteSpace(tabLabel) ? Label : tabLabel };
				caption.Attributes.Add("clreplaced", "tab-replacedle");
				container.Controls.Add(caption);
			}

			container.Controls.Add(tabTable);

			foreach (var columnElement in Node.XPathSelectElements("columns/column"))
			{
				var col = new HtmlGenericControl("div");
				col.Attributes.Add("clreplaced", "tab-column");
				tabTable.Controls.Add(col);

				var xAttribute = columnElement.Attribute("width");
				if (xAttribute != null)
				{
					col.Style.Add("width", xAttribute.Value);
				}

				var wrapper = new HtmlGenericControl("div");
				col.Controls.Add(wrapper);

				var rowTemplateFactory = new TableLayoutRowTemplateFactory(LanguageCode);

				var sectionTemplates = columnElement.XPathSelectElements("sections/section")
					.Select(section => new TableLayoutSectionTemplate(section, LanguageCode, EnreplacedyMetadata, CellTemplateFactory, rowTemplateFactory, _webformMetadata) { MappingFieldCollection = MappingFieldCollection });

				foreach (var template in sectionTemplates)
				{
					template.InstantiateIn(wrapper);
				}
			}
		}

19 Source : XNodeExtensions.cs
with MIT License
from Adoxio

public static bool TryGetAttributeValue(this XNode startingNode, string elementXPath, string attributeName, out string attributeValue)
		{
			attributeValue = null;

			var element = startingNode.XPathSelectElement(elementXPath);

			if (element == null)
			{
				return false;
			}

			var attribute = element.Attribute(XName.Get(attributeName));

			if (attribute == null)
			{
				return false;
			}

			attributeValue = attribute.Value;

			return true;
		}

19 Source : SubjectControlTemplate.cs
with MIT License
from Adoxio

private void PopulateDropDown(DropDownList dropDown)
		{
			if (dropDown.Items.Count > 0)
			{
				return;
			}
			
			var empty = new Lisreplacedem(string.Empty, string.Empty);
			empty.Attributes["label"] = " ";
			dropDown.Items.Add(empty);

			var context = CrmConfigurationManager.CreateContext();

			var service = CrmConfigurationManager.CreateService();

			// By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that enreplacedy and we must query to find the default view.  Saved Query enreplacedy's QueryType code 64 indicates a lookup view.

			var view = Metadata.LookupViewID == Guid.Empty ? context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue<string>("returnedtypecode") == "subject" && s.GetAttributeValue<bool?>("isdefault").GetValueOrDefault(false) && s.GetAttributeValue<int>("querytype") == 64) : context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue<Guid>("savedqueryid") == Metadata.LookupViewID);

			List<Enreplacedy> subjects;

			if (view != null)
			{
				var fetchXML = view.GetAttributeValue<string>("fetchxml");

				var xElement = XElement.Parse(fetchXML);

				var parentsubjectElement = xElement.Descendants("attribute").FirstOrDefault(e =>
																					{
																						var xAttribute = e.Attribute("name");
																						return xAttribute != null && xAttribute.Value == "parentsubject";
																					});

				if (parentsubjectElement == null)
				{
					//If fetchxml does not contain the parentsubject attribute then it must be injected so the results can be organized in a hierarchical order.

					var enreplacedyElement = xElement.Element("enreplacedy");

					if (enreplacedyElement == null)
					{
						return;
					}

					var p = new XElement("attribute", new XAttribute("name", "parentsubject"));

					enreplacedyElement.Add(p);

					fetchXML = xElement.ToString();
				}
				
				var data = service.RetrieveMultiple(new FetchExpression(fetchXML));

				if (data == null || data.Enreplacedies == null)
				{
					return;
				}

				subjects = data.Enreplacedies.ToList();
			}
			else
			{
				subjects = context.CreateQuery("subject").ToList();
			}

			var parents = subjects.Where(s => s.GetAttributeValue<EnreplacedyReference>("parentsubject") == null).OrderBy(s => s.GetAttributeValue<string>("replacedle"));

			foreach (var parent in parents)
			{
				if (parent == null)
				{
					continue;
				}

				dropDown.Items.Add(new Lisreplacedem(parent.GetAttributeValue<string>("replacedle"), parent.Id.ToString()));

				var parentId = parent.Id;

				var children = subjects.Where(s => s.GetAttributeValue<EnreplacedyReference>("parentsubject") != null && s.GetAttributeValue<EnreplacedyReference>("parentsubject").Id == parentId).OrderBy(s => s.GetAttributeValue<string>("replacedle"));

				AddChildItems(dropDown, subjects, children, 1);
			}
		}

19 Source : SavedQueryView.cs
with MIT License
from Adoxio

private string SetSortExpression(XElement fetchXml)
		{
			var enreplacedyElement = fetchXml.XPathSelectElement("//enreplacedy");

			if (enreplacedyElement == null)
			{
				return string.Empty;
			}

			var orderElements = enreplacedyElement.Elements("order").ToArray();
			var orderby = orderElements.Select(orderElement => orderElement.Attribute("descending").Value == "true" ? orderElement.Attribute("attribute").Value + " DESC" : orderElement.Attribute("attribute").Value + " ASC").ToArray();
			var sortExpression = string.Join(",", orderby);
			return sortExpression;
		}

19 Source : SavedQueryView.cs
with MIT License
from Adoxio

private static bool TryGetAttributeMetadataFromLinkEnreplacedyAlias(OrganizationServiceContext serviceContext, string aliasAttributeName, XElement fetchXml, out AttributeMetadata metadata)
		{
			metadata = null;

			var aliasAttributeNameMatch = Regex.Match(aliasAttributeName, @"^(?<alias>\w+)\.(?<attributeName>\w+)$", RegexOptions.ExplicitCapture);

			if (!aliasAttributeNameMatch.Success)
			{
				return false;
			}

			var alias = aliasAttributeNameMatch.Groups["alias"].Value;
			var attributeName = aliasAttributeNameMatch.Groups["attributeName"].Value;

			var linkEnreplacedyElement = fetchXml.XPathSelectElement("//link-enreplacedy[@alias='{0}']".FormatWith(alias));

			if (linkEnreplacedyElement == null)
			{
				return false;
			}

			var linkEnreplacedyNameAttribute = linkEnreplacedyElement.Attribute("name");

			if (linkEnreplacedyNameAttribute == null)
			{
				return false;
			}

			var response = (RetrieveEnreplacedyResponse)serviceContext.Execute(new RetrieveEnreplacedyRequest
			{
				LogicalName = linkEnreplacedyNameAttribute.Value,
				EnreplacedyFilters = EnreplacedyFilters.Attributes
			});

			if (response == null || response.EnreplacedyMetadata == null)
			{
				return false;
			}

			if (!TryGetAttributeMetadata(response.EnreplacedyMetadata, attributeName, out metadata))
			{
				return false;
			}

			return true;
		}

19 Source : SavedQueryColumnsGenerator.cs
with MIT License
from Adoxio

private static bool TryGetLabelFromLinkEnreplacedyAlias(OrganizationServiceContext serviceContext, EnreplacedyMetadata enreplacedyMetadata, string aliasAttributeName, XElement fetchXml, int languageCode, out string label)
		{
			label = null;

			var aliasAttributeNameMatch = Regex.Match(aliasAttributeName, @"^(?<alias>\w+)\.(?<attributeName>\w+)$", RegexOptions.ExplicitCapture);

			if (!aliasAttributeNameMatch.Success)
			{
				return false;
			}

			var alias = aliasAttributeNameMatch.Groups["alias"].Value;
			var attributeName = aliasAttributeNameMatch.Groups["attributeName"].Value;

			var linkEnreplacedyElement = fetchXml.XPathSelectElement("//link-enreplacedy[@alias='{0}']".FormatWith(alias));

			if (linkEnreplacedyElement == null)
			{
				return false;
			}

			var linkEnreplacedyNameAttribute = linkEnreplacedyElement.Attribute("name");

			if (linkEnreplacedyNameAttribute == null)
			{
				return false;
			}

			var response = (RetrieveEnreplacedyResponse)serviceContext.Execute(new RetrieveEnreplacedyRequest
			{
				LogicalName = linkEnreplacedyNameAttribute.Value,
				EnreplacedyFilters = EnreplacedyFilters.Attributes
			});

			if (response == null || response.EnreplacedyMetadata == null)
			{
				return false;
			}

			string linkAttributeLabel;

			if (!TryGetLabelFromAttributeMetadata(response.EnreplacedyMetadata, attributeName, languageCode, out linkAttributeLabel))
			{
				return false;
			}

			var linkEnreplacedyToAttribute = linkEnreplacedyElement.Attribute("to");

			if (linkEnreplacedyToAttribute == null)
			{
				label = linkAttributeLabel;

				return true;
			}

			string linkRelationshipLabel;

			if (!TryGetLabelFromAttributeMetadata(enreplacedyMetadata, linkEnreplacedyToAttribute.Value, languageCode, out linkRelationshipLabel))
			{
				label = linkAttributeLabel;

				return true;
			}

			label = "{0} ({1})".FormatWith(linkAttributeLabel, linkRelationshipLabel);

			return true;
		}

19 Source : SavedQueryColumnsGenerator.cs
with MIT License
from Adoxio

public ICollection GenerateFields(Control control)
		{
			var layoutXml = XElement.Parse(SavedQuery.GetAttributeValue<string>("layoutxml"));
			var cellNames = layoutXml.Element("row").Elements("cell").Select(cell => cell.Attribute("name")).Where(name => name != null);
			var disabledSortCellNames = layoutXml.Element("row").Elements("cell")
						.Where(cell => cell.Attribute("disableSorting") != null && cell.Attribute("disableSorting").Value == "1")
						.Where(cell => cell.Attribute("name") != null)
						.Select(cell => cell.Attribute("name").Value);
			var fetchXml = XElement.Parse(SavedQuery.GetAttributeValue<string>("fetchxml"));
			var enreplacedyName = fetchXml.Element("enreplacedy").Attribute("name").Value;

			var response = (RetrieveEnreplacedyResponse)ServiceContext.Execute(new RetrieveEnreplacedyRequest
			{
				LogicalName = enreplacedyName,
				EnreplacedyFilters = EnreplacedyFilters.Attributes
			});

			if (response == null || response.EnreplacedyMetadata == null)
			{
				return new DataControlFieldCollection();
			}
			
			if (LanguageCode == 0)
			{
				LanguageCode = HttpContext.Current?.GetCrmLcid() ?? CultureInfo.CurrentCulture.LCID;
			}
			
			var fields =
				from name in cellNames
				let label = GetLabel(ServiceContext, response.EnreplacedyMetadata, name.Value, fetchXml, LanguageCode)
				where label != null
				select new BoundField
				{
					DataField = name.Value,
					SortExpression = disabledSortCellNames.Contains(name.Value) ? string.Empty : name.Value,
					HeaderText = label
				};

			return fields.ToArray();
		}

19 Source : SavedQueryView.cs
with MIT License
from Adoxio

private static bool TryGetLabelFromLinkEnreplacedyAlias(OrganizationServiceContext serviceContext, EnreplacedyMetadata enreplacedyMetadata, string aliasAttributeName, XElement fetchXml, int languageCode, string aliasColumnNameStringFormat, out string label)
		{
			label = null;

			var aliasAttributeNameMatch = Regex.Match(aliasAttributeName, @"^(?<alias>\w+)\.(?<attributeName>\w+)$", RegexOptions.ExplicitCapture);

			if (!aliasAttributeNameMatch.Success)
			{
				return false;
			}

			var alias = aliasAttributeNameMatch.Groups["alias"].Value;
			var attributeName = aliasAttributeNameMatch.Groups["attributeName"].Value;

			var linkEnreplacedyElement = fetchXml.XPathSelectElement("//link-enreplacedy[@alias='{0}']".FormatWith(alias));

			if (linkEnreplacedyElement == null)
			{
				return false;
			}

			var linkEnreplacedyNameAttribute = linkEnreplacedyElement.Attribute("name");

			if (linkEnreplacedyNameAttribute == null)
			{
				return false;
			}

			var response = (RetrieveEnreplacedyResponse)serviceContext.Execute(new RetrieveEnreplacedyRequest
			{
				LogicalName = linkEnreplacedyNameAttribute.Value,
				EnreplacedyFilters = EnreplacedyFilters.Attributes
			});

			if (response == null || response.EnreplacedyMetadata == null)
			{
				return false;
			}

			string linkAttributeLabel;

			if (!TryGetLabelFromAttributeMetadata(response.EnreplacedyMetadata, attributeName, languageCode, out linkAttributeLabel))
			{
				return false;
			}

			var linkEnreplacedyToAttribute = linkEnreplacedyElement.Attribute("to");

			if (linkEnreplacedyToAttribute == null)
			{
				label = linkAttributeLabel;

				return true;
			}

			string linkRelationshipLabel;

			if (!TryGetLabelFromAttributeMetadata(enreplacedyMetadata, linkEnreplacedyToAttribute.Value, languageCode, out linkRelationshipLabel))
			{
				label = linkAttributeLabel;

				return true;
			}

			label = aliasColumnNameStringFormat.FormatWith(linkAttributeLabel, linkRelationshipLabel);

			return true;
		}

19 Source : XNodeUtility.cs
with MIT License
from Adoxio

public static bool TryGetAttributeValue(XNode startingNode, string elementXPath, string attributeName, out string attributeValue)
		{
			attributeValue = null;

			var element = startingNode.XPathSelectElement(elementXPath);

			if (element == null)
			{
				return false;
			}

			var attribute = element.Attribute(XName.Get(attributeName));

			if (attribute == null)
			{
				return false;
			}

			attributeValue = attribute.Value;

			return true;
		}

19 Source : CrmSavedQueryColumnsGenerator.cs
with MIT License
from Adoxio

public ICollection GenerateFields(Control control)
		{
			var layoutXml = XElement.Parse(_savedQuery.GetAttributeValue<string>("layoutxml"));

			var cellNames = layoutXml.Element("row").Elements("cell").Select(cell => cell.Attribute("name")).Where(name => name != null);

			var fetchXml = XElement.Parse(_savedQuery.GetAttributeValue<string>("fetchxml"));

			var enreplacedyName = fetchXml.Element("enreplacedy").Attribute("name").Value;

			var response = _context.Execute(new RetrieveEnreplacedyRequest { LogicalName = enreplacedyName, EnreplacedyFilters = EnreplacedyFilters.Attributes }) as RetrieveEnreplacedyResponse;
			var attributeMetadatas = response.EnreplacedyMetadata.Attributes;

			var fields =
				from name in cellNames
				let attributeMetadata = attributeMetadatas.FirstOrDefault(metadata => metadata.LogicalName == name.Value)
				where attributeMetadata != null
				select new BoundField
				{
					DataField = name.Value,
					SortExpression = name.Value,
					HeaderText = attributeMetadata.DisplayName.UserLocalizedLabel.Label // MSBug #120122: No need to URL encode--encoding is handled by webcontrol rendering layer.
				};

			return fields.ToList();
		}

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static List<string> GetOverworldCreatureList()
        {
            List<string> stringifiedCreatures = new List<string>();
            // load
            XElement root = XElement.Load("res/data/OverworldCreatureTypes.xml");
            IEnumerable<XElement> creatures =
                from el in root.Elements("creature")
                select el;
            //convert
            foreach (XElement c in creatures)
                stringifiedCreatures.Add(System.Convert.ToString(ReadAttribute(c.Attribute("name"))));
            return stringifiedCreatures;
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static Dungeon GetNextDungeon(int preferredLvl)
        {
            Dungeon dungeon = null;
            XElement dungeonData = null;

            // load all the dungeons
            XElement root = XElement.Load("res/data/DungeonTypes.xml");
            IEnumerable<XElement> dungeons =
                from el in root.Elements("dungeon")
                select el;

            // get the correct dungeon based on lvl (need to expand this to accomodate multiple dungeons)
            foreach (XElement dun in dungeons) {
                int minLvl;
                int maxLvl;
                XElement lvl_range = dun.Element("level_range");
                minLvl = System.Convert.ToInt32(ReadAttribute(lvl_range.Attribute("min_lvl")));
                maxLvl = System.Convert.ToInt32(ReadAttribute(lvl_range.Attribute("max_lvl")));

                if (preferredLvl >= minLvl && preferredLvl <= maxLvl) {
                    dungeonData = dun;
                    break;
                }
            }

            // convert the dungeon's data into a clreplaced
            string name = "";
            int floors;
            List<string> monsters = new List<string>();

            List<string> names = new List<string>();
            foreach (XElement el in dungeonData.Element("names").Elements("name"))
                names.Add(ReadElement(el));
            name = names[Program.RNG.Next(0, names.Count)];

            Enum.TryParse(ReadAttribute(dungeonData.Element("algorithms").Element("algorithm").Attribute("name")), out DungeonType dungeonType);

            floors = System.Convert.ToInt32(ReadAttribute(dungeonData.Element("floors").FirstAttribute));

            // get the monsters
            // get permanent monster types
            string monsterNames = ReadAttribute(dungeonData.Element("monster_types").Attribute("persistent"));
            int i = 0;
            monsters.Add("");
            foreach (char c in monsterNames) {
                if (c == ' ') { i++; monsters.Add(""); }
                else
                    monsters[i] = monsters[i] + c;
            }

            // pick random unique monster types
            List<string> uniqueMonsters = new List<string>();
            int uniqueCount = System.Convert.ToInt32(ReadAttribute(dungeonData.Element("monster_types").Attribute("unique_count")));
            monsterNames = ReadAttribute(dungeonData.Element("monster_types").Attribute("unique"));
            i = 0;
            uniqueMonsters.Add("");
            foreach (char c in monsterNames) {
                if (c == ' ') { i++; uniqueMonsters.Add(""); }
                else
                    uniqueMonsters[i] = uniqueMonsters[i] + c;
            }

            int max = monsters.Count + uniqueCount;
            while (monsters.Count < max) {
                int rand = Program.RNG.Next(0, uniqueMonsters.Count);
                monsters.Add(uniqueMonsters[rand]);
                uniqueMonsters.RemoveAt(rand);
            }

            dungeon = new Dungeon(name, dungeonType, monsters, floors);

            return dungeon;
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static Monster GetMonster(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
        {
            XElement monsterData = null;

            // load all the effects
            XElement root = XElement.Load( "res/data/MonsterTypes.xml" );
            IEnumerable<XElement> monsters =
                from el in root.Elements( "monster" )
                select el;

            // choose the right effect
            foreach ( XElement m in monsters )
                if ( ReadAttribute( m.FirstAttribute ) == name )
                    monsterData = m;

            if ( monsterData == null )
                return null;

            byte graphic = System.Convert.ToByte( ReadAttribute( monsterData.Attribute( "ascii_char" ) ) );
            string faction = System.Convert.ToString( ReadAttribute( monsterData.Attribute( "faction" ) ) );
            int sightDist = System.Convert.ToInt32( ReadAttribute( monsterData.Attribute( "sight_dist" ) ) );

            byte r = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "r" ) ) ),
                 g = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "g" ) ) ),
                 b = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "b" ) ) );
            Color? color = new Color( r, g, b );

            Enum.TryParse(ReadElement(monsterData.Element("diet")), out DietType diet);

            IEnumerable<XElement> majorAttData = from el in monsterData.Element( "clreplaced" ).Element( "major_attributes" ).Elements( "attribute" )
                                                 select el;
            List<Attribute> majorAtt = new List<Attribute>();
            foreach (XElement attE in majorAttData) {
                Enum.TryParse( ReadElement( attE ), out Attribute att );
                majorAtt.Add( att );
            } // translate IEnumerable to List

            IEnumerable<XElement> majorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "major_skills" ).Elements( "skill" )
                                                    select el;
            List<Skill> majorSkills = new List<Skill>();
            foreach ( XElement skillE in majorSkillsData ) {
                Enum.TryParse( ReadElement( skillE ), out Skill skill );
                majorSkills.Add( skill );
            } // translate IEnumerable to List

            IEnumerable<XElement> minorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "minor_skills" ).Elements( "skill" )
                                                    select el;
            List<Skill> minorSkills = new List<Skill>();
            foreach (XElement skillE in minorSkillsData) {
                Enum.TryParse( ReadElement( skillE ), out Skill skill );
                minorSkills.Add( skill );
            } // translate IEnumerable to List

            Clreplaced uClreplaced = new Clreplaced( majorAtt, majorSkills, minorSkills );
            
            IEnumerable<XElement> baseDesiresData = from el in monsterData.Element( "base_desires" ).Elements( "desire_type" )
                                                    select el;
            Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
            foreach (XElement desireTypeE in baseDesiresData) {
                Enum.TryParse( ReadAttribute( desireTypeE.FirstAttribute ), out DesireType desireType );
                baseDesires.Add( desireType, System.Convert.ToInt32( ReadAttribute( desireTypeE.LastAttribute ) ) );
            } // translate IEnumerable to List

            return new Monster( map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic );
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static Animal GetAnimal(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
        {
            XElement creatureData = null;

            // load all the creatures
            XElement root = XElement.Load("res/data/OverworldCreatureTypes.xml");
            IEnumerable<XElement> creatures =
                from el in root.Elements("creature")
                select el;

            // choose the right creature
            foreach (XElement c in creatures)
                if (ReadAttribute(c.FirstAttribute).Equals(name))
                    creatureData = c;

            if (creatureData == null)
                return null;

            byte graphic = System.Convert.ToByte(ReadAttribute(creatureData.Attribute("ascii_char")));
            string faction = System.Convert.ToString(ReadAttribute(creatureData.Attribute("faction")));
            int sightDist = System.Convert.ToInt32(ReadAttribute(creatureData.Attribute("sight_dist")));

            byte r = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("r"))),
                 g = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("g"))),
                 b = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("b")));
            Color? color = new Color(r, g, b);

            Enum.TryParse(ReadElement(creatureData.Element("diet")), out DietType diet);

            IEnumerable<XElement> majorAttData = from el in creatureData.Element("clreplaced").Element("major_attributes").Elements("attribute")
                                                 select el;
            List<Attribute> majorAtt = new List<Attribute>();
            foreach (XElement attE in majorAttData) {
                Enum.TryParse(ReadElement(attE), out Attribute att);
                majorAtt.Add(att);
            }

            IEnumerable<XElement> majorSkillsData = from el in creatureData.Element("clreplaced").Element("major_skills").Elements("skill")
                                                    select el;
            List<Skill> majorSkills = new List<Skill>();
            foreach (XElement skillE in majorSkillsData) {
                Enum.TryParse(ReadElement(skillE), out Skill skill);
                majorSkills.Add(skill);
            }

            IEnumerable<XElement> minorSkillsData = from el in creatureData.Element("clreplaced").Element("minor_skills").Elements("skill")
                                                    select el;
            List<Skill> minorSkills = new List<Skill>();
            foreach (XElement skillE in minorSkillsData) {
                Enum.TryParse(ReadElement(skillE), out Skill skill);
                minorSkills.Add(skill);
            }

            Clreplaced uClreplaced = new Clreplaced(majorAtt, majorSkills, minorSkills);

            IEnumerable<XElement> baseDesiresData = from el in creatureData.Element("base_desires").Elements("desire_type")
                                                    select el;
            Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
            foreach (XElement desireTypeE in baseDesiresData) {
                Enum.TryParse(ReadAttribute(desireTypeE.FirstAttribute), out DesireType desireType);
                baseDesires.Add(desireType, System.Convert.ToInt32(ReadAttribute(desireTypeE.LastAttribute)));
            }

            return new Animal(map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic);
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static Plant GetPlant(string name)
        {
            XElement plantData = null;

            // load all the plants
            XElement root = XElement.Load("res/data/PlantTypes.xml");
            IEnumerable<XElement> plants =
                from el in root.Elements("plant")
                select el;

            // choose the right creature
            foreach (XElement p in plants)
                if (ReadAttribute(p.FirstAttribute).Equals(name))
                    plantData = p;

            if (plantData == null)
                return null;

            bool edible = System.Convert.ToBoolean(ReadAttribute(plantData.Element("edible").Attribute("bool")));
            int growthInterval = System.Convert.ToInt32(ReadAttribute(plantData.Attribute("growth_interval")));
            int seedRadius = System.Convert.ToInt32(ReadAttribute(plantData.Attribute("seed_radius")));

            byte r = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("r"))),
                 g = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("g"))),
                 b = System.Convert.ToByte(ReadAttribute(plantData.Element("fore_color").Attribute("b")));
            Color? foreColor = new Color(r, g, b);

            IEnumerable<XElement> growthStagesTemp =
                from el in plantData.Element("growth_stages").Elements("growth_stage")
                select el;
            List<byte> growthStages = new List<byte>();
            foreach (XElement growthStage in growthStagesTemp)
                growthStages.Add(System.Convert.ToByte(ReadAttribute(growthStage.Attribute("graphic"))));

            string requirement;
            if (ReadAttribute(plantData.Element("requirement").FirstAttribute).Equals(""))
                requirement = "";
            else {
                requirement =
                    ReadAttribute(plantData.Element("requirement").FirstAttribute)
                    + ';'
                    + ReadAttribute(plantData.Element("requirement").Attribute("type"))
                    + ';'
                    + ReadAttribute(plantData.Element("requirement").Attribute("dist"));
            }

            return new Plant(growthStages[0], name, growthInterval, seedRadius, growthStages, requirement, edible, foreColor);
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static WeaponEnchantment GetWeaponEnchantment( string enchantName )
        {
            WeaponEnchantment wEnchant = null;
            XElement wEnchantData = null;

            // load all the enchantments
            XElement root = XElement.Load("res/data/WeaponEnchantTypes.xml");
            IEnumerable<XElement> enchants =
                from el in root.Elements("enchantment")
                select el;

            // choose the right enchantment
            foreach (XElement e in enchants)
                if (ReadAttribute(e.Attribute("name")).Equals(enchantName))
                    wEnchantData = e;

            if (wEnchantData == null)
                return null;

            string name = enchantName;

            List<XElement> partNames = wEnchantData.Element("part_names").Elements().ToList();
            string partName = ReadAttribute(partNames[Program.RNG.Next(0, partNames.Count)].FirstAttribute);

            Enum.TryParse(ReadAttribute(wEnchantData.Attribute("damage_type")), out DamageType damageType);
            Effect appliedEffect = GetEffect(ReadAttribute(wEnchantData.Attribute("applied_effect")));
            int victimDamage = Program.RNG.Next(System.Convert.ToInt32(ReadAttribute(wEnchantData.Element("victim_damage").FirstAttribute)), System.Convert.ToInt32(ReadAttribute(wEnchantData.Element("victim_damage").LastAttribute)));

            wEnchant = new WeaponEnchantment(name, partName, damageType, victimDamage, appliedEffect);

            return wEnchant;
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static Effect GetNextEffect()
        {
            // load all the effects
            XElement root = XElement.Load("res/data/EffectTypes.xml");
            IEnumerable<XElement> effects =
                from el in root.Elements("effect")
                select el;

            List<XAttribute> names = new List<XAttribute>();

            foreach (XElement e in effects)
                names.Add(e.Attribute("name"));

            return GetEffect(ReadAttribute(names[Program.RNG.Next(0, names.Count)]));
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static string GetNextTip()
        {
            string tip = "";

            XElement root = XElement.Load("res/data/GameTipList.xml");
            IEnumerable<XElement> tips =
                from el in root.Elements("tip")
                select el;

            List<XElement> tipList = new List<XElement>();

            foreach (XElement el in tips)
                tipList.Add(el);

            if (tipList.Count == 0)
                throw new System.Exception();

            int index = Program.RNG.Next(0, tipList.Count);
            if (readTips.Count == tipList.Count)
                readTips = new List<int>();
            while (readTips.Contains(index))
            {
                index = Program.RNG.Next(0, tipList.Count);
            }
            tip = ReadAttribute(tipList[index].Attribute("text"));
            readTips.Add(index);

            return tip;
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static List<string> GetPlantList()
        {
            List<string> stringifiedPlants = new List<string>();
            // load
            XElement root = XElement.Load("res/data/PlantTypes.xml");
            IEnumerable<XElement> plants =
                from el in root.Elements("plant")
                select el;
            // convert
            foreach (XElement p in plants)
                stringifiedPlants.Add(System.Convert.ToString(ReadAttribute(p.Attribute("name"))));
            return stringifiedPlants;
        }

19 Source : DataReader.cs
with GNU General Public License v3.0
from aenemenate

public static WeaponEnchantment GetNextWeaponEnchantment()
        {
            // load all the enchantments
            XElement root = XElement.Load("res/data/WeaponEnchantTypes.xml");
            IEnumerable<XElement> enchants =
                from el in root.Elements("enchantment")
                select el;

            List<XAttribute> names = new List<XAttribute>();

            foreach (XElement e in enchants)
                names.Add(e.Attribute("name"));

            return GetWeaponEnchantment(ReadAttribute(names[Program.RNG.Next(0, names.Count)]));
        }

19 Source : XmlMember.cs
with Mozilla Public License 2.0
from agebullhu

public static void Load(string path)
        {
            if (!File.Exists(path))
                return;
            var xRoot = XElement.Load(path);
            var xElement = xRoot.Element("members");
            if (xElement == null) return;
            var chars = new[] { ':', '(' };
            var chars2 = new[] { '`', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
            var members = from p in xElement.Elements("member")
                          let name = p.Attribute("name")
                          where !string.IsNullOrEmpty(name?.Value)
                          let summary = p.Element("summary")
                          let remarks = p.Element("remarks")
                          let seealso = p.Element("seealso")
                          let value = p.Element("value")
                          let example = p.Element("example")
                          let returns = p.Element("returns")
                          let paramss = p.Elements("param")
                          let np = name.Value.Split(chars)
                          select new XmlMember
                          {
                              Type = np[0],
                              Name = np[1].TrimEnd(chars2),
                              Caption = summary?.Value.ConverToAscii(),
                              Description = remarks?.Value.ConverToAscii(),
                              Seealso = seealso?.Value,
                              Value = value?.Value,
                              Example = example?.Value,
                              Returns = returns?.Value,
                              XArguments = paramss
                          };

            HelpXml.AddRange(members);
        }

19 Source : XmlMember.cs
with Mozilla Public License 2.0
from agebullhu

private static void Load(replacedembly replacedembly)
        {
            var file = Path.Combine(Path.GetDirectoryName(replacedembly.Location),Path.GetFileNameWithoutExtension(replacedembly.Location) + ".xml");
            replacedemblys.Add(replacedembly, "");
            if (!File.Exists(file))
                return ;
            XElement xRoot = XElement.Load(file);
            var xElement = xRoot.Element("members");
            if (xElement == null)
            {
                return ;
            }
            var members = from p in xElement.Elements("member")
                let name = p.Attribute("name")
                where !string.IsNullOrEmpty(name?.Value) && name.Value[0] != 'M'
                let summary = p.Element("summary")
                let remarks = p.Element("remarks")
                let np = name.Value.Split(':', '(')
                select new XmlMember
                {
                    Type = np[0],
                    Name = np[1],
                    Remark = remarks?.Value,
                    Summary = summary?.Value.Trim()
                };
            HelpXml.AddRange(members);
        }

19 Source : XMLStuff.cs
with GNU General Public License v3.0
from Albo1125

public static List<TransportWorldDistrict> LoadTransportWorldDistrictsFromXMLFile(string file)
        {
            TransportWorldDistrict DefaultCityDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.City,
                DriverModels = new Model[] { "S_M_Y_COP_01" },
                PreplacedengerModels = new Model[] { "S_F_Y_COP_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("POLICET", -1, new int[] { }) }
            };
            TransportWorldDistrict DefaultCountrysideDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.LosSantosCountryside,
                DriverModels = new Model[] { "S_M_Y_SHERIFF_01" },
                PreplacedengerModels = new Model[] { "S_F_Y_SHERIFF_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("SHERIFF2", -1, new int[] { }) }
            };
            TransportWorldDistrict DefaultBlaineDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.BlaineCounty,
                DriverModels = new Model[] { "S_M_Y_SHERIFF_01" },
                PreplacedengerModels = new Model[] { "S_F_Y_SHERIFF_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("SHERIFF2", -1, new int[] { }) }
            };

            TransportWorldDistrict DefaulreplacederDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.Water,
                DriverModels = new Model[] { "s_m_y_uscg_01" },
                PreplacedengerModels = new Model[] { "s_m_y_uscg_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("PREDATOR", -1, new int[] { }) }
            };

            try
            {

                #region defaultdoreplacedent
                if (!File.Exists(file))
                {
                    Directory.CreateDirectory(Directory.GetParent(file).FullName);
                    new XDoreplacedent(
                    new XElement("ArrestManager",
                        new XComment(@"These Transport World Districts are used if you call for transport within a certain world district and you don't have a transport region set up for that district.

    Multiple Transport World Districts can be set up for more than one zone.

    In that case, Arrest Manager will select a random one from the ones that you've specified for that zone.
    There must be at least one Transport World District for each of the following:

    Valid district names are: City, LosSantosCountryside, BlaineCounty, Water.

    Certain restrictions & conditions apply: Driver & Preplacedenger & Vehicle models must be valid.
    A vehicle must have at least 4 free seats and must be a Police vehicle(with the exception of the RIOT van).This means a FLAG_LAW_ENFORCEMENT in vehicles.meta must be present.
    Water districts must have boats as vehicles.

    LiveryNumber and ExtraNumbers are optional.
    For LiveryNumber & ExtraNumbers: Keep in mind the code starts counting at 0.If a LiveryNumber is 1 in OpenIV, it will be 0 in code so you must enter 0.
    If the LiveryNumber is 2 in OpenIV it will be 1 in code so you must enter 1 etc.

    ExtraNumbers must be separated by commas, e.g. 2,3,4,5.

    Naturally, you can add as many TransportWorldDistricts as you like - just keep them between the <ArrestManager> and </ArrestManager> tags.
    The below ones are meant as examples of what you can do.
    The default XML file that comes with the Arrest Manager download (this one, if you haven't changed it) works ingame.

    There's no need to change anything if you don't want to.

    If you don't set anything at all for a certain district (not recommended) a very basic default will be set by Arrest Manager itself.


    Here you can change the ped that's driving the transport vehicle. You can find all valid values here: http://ragepluginhook.net/PedModels.aspx

    Police unit uniforms
    Male City Police: s_m_y_cop_01
    Female City Police: s_f_y_cop_01
    Female Sheriff: s_f_y_sheriff_01
    Male Sheriff: s_m_y_sheriff_01
    Male Highway: s_m_y_hwaycop_01
    Prison Guard: s_m_m_prisguard_01

    Police Vehicle Examples: POLICE, POLICE2, POLICE3, POLICE4, POLICET, SHERIFF, SHERIFF2"


                        ), new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "City"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICET"), new XAttribute("LiveryNumber", "0")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE2"), new XAttribute("ExtraNumbers", "1")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE3"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "1"))
                        ),

                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "City"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICET")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE2")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE3"))
                            ),

                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "LosSantosCountryside"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Vehicle", new XAttribute("Model", "SHERIFF2"))
                            ),

                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "BlaineCounty"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Vehicle", new XAttribute("Model", "SHERIFF2"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "2,3,4"))
                            ),
                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "Water"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_USCG_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_USCG_01")),
                            new XElement("Vehicle", new XAttribute("Model", "PREDATOR"))
                            )
                        )

                    ).Save(file);
                    Game.LogTrivial("Transport world district file did not exist. Created default.");
                }
                #endregion
                XDoreplacedent xdoc = XDoreplacedent.Load(file);
                char[] trim = new char[] { '\'', '\"', ' ' };
                
                List<TransportWorldDistrict> trnswrlddistrs = xdoc.Descendants("TransportWorldDistrict").Select(x => new TransportWorldDistrict()
                {
                    WorldDistrict = (Zones.WorldDistricts)Enum.Parse(typeof(Zones.WorldDistricts), ((string)x.Attribute("DistrictName")).Trim(trim)),
                    DriverModels = (x.Elements("Driver").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    PreplacedengerModels = (x.Elements("Preplacedenger").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    VehSettings = (x.Elements("Vehicle").Select(y => new VehicleSettings(new Model((((string)y.Attribute("Model"))).Trim(trim)),
                    (string)y.Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("LiveryNumber")) ? Int32.Parse(((string)y.Attribute("LiveryNumber")).Trim(trim)) : -1,
                    (string)y.Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)y.Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { })).ToArray()),
                    
                }).ToList<TransportWorldDistrict>();
                
                foreach (Zones.WorldDistricts distr in Enum.GetValues(typeof(Zones.WorldDistricts)))
                {
                    if (!trnswrlddistrs.Select(x => x.WorldDistrict).Contains(distr))
                    {
                        Game.LogTrivial("Transport World Districts doesn't contain " + distr.ToString() + ". Adding default.");
                        if (distr == Zones.WorldDistricts.City)
                        {
                            
                            trnswrlddistrs.Add(DefaultCityDistrict);
                        }
                        else if (distr == Zones.WorldDistricts.LosSantosCountryside)
                        {
                            trnswrlddistrs.Add(DefaultCountrysideDistrict);
                        }
                        else if (distr == Zones.WorldDistricts.BlaineCounty)
                        {
                            trnswrlddistrs.Add(DefaultBlaineDistrict);
                        }
                        else if (distr == Zones.WorldDistricts.Water)
                        {
                            trnswrlddistrs.Add(DefaulreplacederDistrict);
                        }

                    }
                }

                return trnswrlddistrs;
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (Exception e)
            {
                Game.LogTrivial("Arrest Manager encountered an exception reading \'" + file + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~Error reading Transport World Districts.xml. Setting default values.");
            }

            return new List<TransportWorldDistrict>() { DefaultCityDistrict, DefaultBlaineDistrict, DefaultCountrysideDistrict };
        }

19 Source : XMLStuff.cs
with GNU General Public License v3.0
from Albo1125

public static List<TransportRegion> LoadTransportRegionsFromXMLFile(string file)
        {
            try
            {
                #region defaultdoreplacedent
                if (!File.Exists(file))
                {
                    Directory.CreateDirectory(Directory.GetParent(file).FullName);
                    new XDoreplacedent(
                    new XElement("ArrestManager",
                        new XComment(@"These Transport Regions are used to override the Transport World Districts if you call for transport in a certain Zone that you've set up below.
	Multiple regions can be set up for one zone - in that case, Arrest Manager will select a random transport region from the ones that you've specified for that zone.
	A list of zone names can be found in the Doreplacedentation and Licence folder.
		
	The same restrictions apply here as in the world districts file: Driver & Preplacedenger & Vehicle models must be valid. 
	A vehicle must have at least 4 free seats and must be a Police vehicle (with the exception of the RIOT van).
		
	LiveryNumber and ExtraNumbers are optional.
	For LiveryNumber&ExtraNumbers: Keep in mind the code starts counting at 0. If a LiveryNumber is 1 in OpenIV, it will be 0 in code so you must enter 0.
	If the LiveryNumber is 2 in OpenIV it will be 1 in code so you must enter 1 etc.
		
	ExtraNumbers must be separated by commas, e.g. 2, 3, 4, 5.


    The default XML file that comes with the Arrest Manager download(this one, if you haven't changed it) works ingame.

    There's no need to change anything if you don't want to.
    Naturally, you can add as many TransportRegions as you like(add them between the < ArrestManager > and </ ArrestManager > tags).The below regions are meant as examples of what you can do.

        Here you can change the ped that's driving the transport vehicle. You can find all valid values here: http://ragepluginhook.net/PedModels.aspx

    Police unit uniforms
    Male City Police: s_m_y_cop_01
    Female City Police: s_f_y_cop_01
    Female Sheriff: s_f_y_sheriff_01
    Male Sheriff: s_m_y_sheriff_01
    Male Highway: s_m_y_hwaycop_01
    Prison Guard: s_m_m_prisguard_01

    Police Vehicle Examples: POLICE, POLICE2, POLICE3, POLICE4, POLICET, SHERIFF, SHERIFF2"),

                        new XElement("TransportRegion",
                            new XAttribute("ZoneName", "East Vinewood"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE4"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "2,3,4"))
                            ),
                        new XElement("TransportRegion",
                            new XAttribute("ZoneName", "West Vinewood"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICET"), new XAttribute("LiveryNumber", "0"))
                            ),
                        new XElement("TransportRegion",
                            new XAttribute("ZoneName", "Sandy Sreplaceds"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Vehicle", new XAttribute("Model", "SHERIFF"))
                            )
                            )).Save(file);



                }
                #endregion
                XDoreplacedent xdoc = XDoreplacedent.Load(file);
                char[] trim = new char[] { '\'', '\"', ' ' };

                List<TransportRegion> trnsregs = xdoc.Descendants("TransportRegion").Select(x => new TransportRegion()
                {
                    ZoneName = ((string)x.Attribute("ZoneName")).Trim(trim),
                    DriverModels = (x.Elements("Driver").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    PreplacedengerModels = (x.Elements("Preplacedenger").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    VehSettings = (x.Elements("Vehicle").Select(y => new VehicleSettings(new Model((((string)y.Attribute("Model"))).Trim(trim)),
                    (string)y.Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("LiveryNumber")) ? Int32.Parse(((string)y.Attribute("LiveryNumber")).Trim(trim)) : -1,
                    (string)y.Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)y.Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { })).ToArray()),
                    //VehicleModel = new Model(((string)x.Element("Vehicle").Attribute("Model")).Trim(trim)),
                    //LiveryNumber = (string)x.Element("Vehicle").Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)x.Element("Vehicle").Attribute("LiveryNumber")) ?  Int32.Parse(((string)x.Element("Vehicle").Attribute("LiveryNumber")).Trim(trim)) : -1,
                    //ExtraNumbers = (string)x.Element("Vehicle").Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)x.Element("Vehicle").Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)x.Element("Vehicle").Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { },
                }).ToList<TransportRegion>();
                
                return trnsregs;
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (Exception e)
            {
                Game.LogTrivial("Arrest Manager encountered an exception reading \'" + file + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~Error reading Transport Regions.xml. Setting default values.");
            }
            return new List<TransportRegion>();
        }

19 Source : CourtSystem.cs
with GNU General Public License v3.0
from Albo1125

private static void DeleteCourtCaseFromXMLFile(string File, CourtCase ccase)
        {
            try
            {
                XDoreplacedent xdoc = XDoreplacedent.Load(File);
                char[] trim = new char[] { '\'', '\"', ' ' };
                List<XElement> CourtCasesToBeDeleted = new List<XElement>();
                CourtCasesToBeDeleted = (from x in xdoc.Descendants("CourtCase") where (((string)x.Attribute("ID")).Trim(trim) == ccase.XMLIdentifier) select x).ToList<XElement>();

                if (CourtCasesToBeDeleted.Count > 0)
                {


                    foreach (XElement ele in CourtCasesToBeDeleted)
                    {



                        ele.Remove();


                    }


                }
                xdoc.Save(File);
            }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered an exception deleting an element from \'" + File + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Error while working with CourtCases.xml.");
            }
        }

19 Source : StatisticsCounter.cs
with GNU General Public License v3.0
from Albo1125

public static void AddCountToStatistic(string Statistic, string PluginName)
        {

            try
            {
                SimpleAES StringEncrypter = new SimpleAES();
                Directory.CreateDirectory(Directory.GetParent(StatisticsFilePath).FullName);
                if (!File.Exists(StatisticsFilePath))
                {

                    new XDoreplacedent(
                        new XElement("LSPDFRPlus")
                    )
                    .Save(StatisticsFilePath);

                }              
                
                string pswd = Environment.UserName;
                
                string EncryptedStatistic = XmlConvert.EncodeName(StringEncrypter.EncryptToString(Statistic + PluginName + pswd));

                string EncryptedPlugin = XmlConvert.EncodeName(StringEncrypter.EncryptToString(PluginName + pswd));
                
                XDoreplacedent xdoc = XDoreplacedent.Load(StatisticsFilePath);
                char[] trim = new char[] { '\'', '\"', ' ' };
                XElement LSPDFRPlusElement;
                if (xdoc.Element("LSPDFRPlus") == null)
                {
                    LSPDFRPlusElement = new XElement("LSPDFRPlus");
                    xdoc.Add(LSPDFRPlusElement);
                }

                LSPDFRPlusElement = xdoc.Element("LSPDFRPlus");
                XElement StatisticElement;
                if (LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).ToList().Count == 0)
                {
                    //Game.LogTrivial("Creating new statistic entry.");
                    StatisticElement = new XElement(EncryptedStatistic);
                    StatisticElement.Add(new XAttribute("Plugin", EncryptedPlugin));
                    LSPDFRPlusElement.Add(StatisticElement);
                }
                StatisticElement = LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).FirstOrDefault();
                int StatisticCount;
                if (StatisticElement.IsEmpty)
                {
                    StatisticCount = 0;
                }
                else
                {
                    string DecryptedStatistic = StringEncrypter.DecryptString(XmlConvert.DecodeName(StatisticElement.Value));
                    //Game.LogTrivial("Decryptedstatistic: " + DecryptedStatistic);
                    int index = DecryptedStatistic.IndexOf(EncryptedStatistic);
                    string cleanPath = (index < 0)
                        ? "0"
                        : DecryptedStatistic.Remove(index, EncryptedStatistic.Length);
                    //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 2"); }
                    
                    index = cleanPath.IndexOf(pswd);
                    cleanPath = (index < 0)
                        ? "0"
                        : cleanPath.Remove(index, pswd.Length);
                    //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 1"); }
                    StatisticCount = int.Parse(cleanPath);


                }
                //Game.LogTrivial("Statisticscount: " + StatisticCount.ToString());
                StatisticCount++;
                string ValueToWrite = StatisticCount.ToString() + pswd;
                int indextoinsertat = LSPDFRPlusHandler.rnd.Next(ValueToWrite.Length);
                ValueToWrite = ValueToWrite.Substring(0, indextoinsertat) + EncryptedStatistic + ValueToWrite.Substring(indextoinsertat);
                //Game.LogTrivial("Valueotwrite: " + ValueToWrite);
                StatisticElement.Value = XmlConvert.EncodeName(StringEncrypter.EncryptToString(ValueToWrite));

                xdoc.Save(StatisticsFilePath);

            }
            catch (System.Threading.ThreadAbortException e) { }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered a statistics exception. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Statistics error.");
            }
        }

19 Source : SmartSystemMenuSettings.cs
with MIT License
from AlexanderPro

public static SmartSystemMenuSettings Read(string fileName, string languageFileName)
        {
            var settings = new SmartSystemMenuSettings();
            var doreplacedent = XDoreplacedent.Load(fileName);
            var languageDoreplacedent = XDoreplacedent.Load(languageFileName);

            settings.ProcessExclusions = doreplacedent
                .XPathSelectElements("/smartSystemMenu/processExclusions/processName")
                .Where(x => !string.IsNullOrWhiteSpace(x.Value))
                .Select(x => x.Value.ToLower())
                .ToList();

            settings.MenuItems.WindowSizeItems = doreplacedent
                .XPathSelectElements("/smartSystemMenu/menuItems/windowSizeItems/item")
                .Select(x => new WindowSizeMenuItem
                {
                    replacedle = x.Attribute("replacedle") != null ? x.Attribute("replacedle").Value : "",
                    Left = !string.IsNullOrEmpty(x.Attribute("left").Value) ? int.Parse(x.Attribute("left").Value) : (int?)null,
                    Top = !string.IsNullOrEmpty(x.Attribute("top").Value) ? int.Parse(x.Attribute("top").Value) : (int?)null,
                    Width = int.Parse(x.Attribute("width").Value),
                    Height = int.Parse(x.Attribute("height").Value),
                    Key1 = x.Attribute("key1") != null && !string.IsNullOrEmpty(x.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key1").Value) : VirtualKeyModifier.None,
                    Key2 = x.Attribute("key2") != null && !string.IsNullOrEmpty(x.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key2").Value) : VirtualKeyModifier.None,
                    Key3 = x.Attribute("key3") != null && !string.IsNullOrEmpty(x.Attribute("key3").Value) ? (VirtualKey)int.Parse(x.Attribute("key3").Value) : VirtualKey.None
                })
                .ToList();

            settings.MenuItems.StartProgramItems = doreplacedent
                .XPathSelectElements("/smartSystemMenu/menuItems/startProgramItems/item")
                .Select(x => new StartProgramMenuItem
                {
                    replacedle = x.Attribute("replacedle") != null ? x.Attribute("replacedle").Value : "",
                    FileName = x.Attribute("fileName") != null ? x.Attribute("fileName").Value : "",
                    Arguments = x.Attribute("arguments") != null ? x.Attribute("arguments").Value : "",
                })
                .ToList();

            settings.MenuItems.Items = doreplacedent
                .XPathSelectElements("/smartSystemMenu/menuItems/items/item")
                .Select(x => {
                    var menuItem = new MenuItem
                    {
                        Name = x.Attribute("name") != null ? x.Attribute("name").Value : "",
                        Show = x.Attribute("show") != null ? x.Attribute("show").Value.ToLower() != "false" : true,
                        Type = x.Attribute("type") != null && !string.IsNullOrEmpty(x.Attribute("type").Value) ? (MenuItemType)Enum.Parse(typeof(MenuItemType), x.Attribute("type").Value, true) : MenuItemType.Item,
                        Key1 = x.Attribute("key1") != null && !string.IsNullOrEmpty(x.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key1").Value) : VirtualKeyModifier.None,
                        Key2 = x.Attribute("key2") != null && !string.IsNullOrEmpty(x.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key2").Value) : VirtualKeyModifier.None,
                        Key3 = x.Attribute("key3") != null && !string.IsNullOrEmpty(x.Attribute("key3").Value) ? (VirtualKey)int.Parse(x.Attribute("key3").Value) : VirtualKey.None
                    };
                    menuItem.Items = menuItem.Type == MenuItemType.Group ?
                    x.XPathSelectElements("./items/item")
                    .Select(y => new MenuItem
                    {
                        Name = y.Attribute("name") != null ? y.Attribute("name").Value : "",
                        Show = y.Attribute("show") != null ? y.Attribute("show").Value.ToLower() != "false" : true,
                        Type = y.Attribute("type") != null && !string.IsNullOrEmpty(y.Attribute("type").Value) ? (MenuItemType)Enum.Parse(typeof(MenuItemType), y.Attribute("type").Value, true) : MenuItemType.Item,
                        Key1 = y.Attribute("key1") != null && !string.IsNullOrEmpty(y.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(y.Attribute("key1").Value) : VirtualKeyModifier.None,
                        Key2 = y.Attribute("key2") != null && !string.IsNullOrEmpty(y.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(y.Attribute("key2").Value) : VirtualKeyModifier.None,
                        Key3 = y.Attribute("key3") != null && !string.IsNullOrEmpty(y.Attribute("key3").Value) ? (VirtualKey)int.Parse(y.Attribute("key3").Value) : VirtualKey.None
                    }).ToList() : new List<MenuItem>();
                    return menuItem;
                })
                .ToList();

            var closerElement = doreplacedent.XPathSelectElement("/smartSystemMenu/closer");
            settings.Closer.Type = closerElement.Attribute("type") != null && !string.IsNullOrEmpty(closerElement.Attribute("type").Value) ? (WindowCloserType)int.Parse(closerElement.Attribute("type").Value) : WindowCloserType.CloseForegroundWindow;
            settings.Closer.Key1 = closerElement.Attribute("key1") != null && !string.IsNullOrEmpty(closerElement.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(closerElement.Attribute("key1").Value) : VirtualKeyModifier.None;
            settings.Closer.Key2 = closerElement.Attribute("key2") != null && !string.IsNullOrEmpty(closerElement.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(closerElement.Attribute("key2").Value) : VirtualKeyModifier.None;
            settings.Closer.MouseButton = closerElement.Attribute("mouseButton") != null && !string.IsNullOrEmpty(closerElement.Attribute("mouseButton").Value) ? (MouseButton)int.Parse(closerElement.Attribute("mouseButton").Value) : MouseButton.None;

            var sizerElement = doreplacedent.XPathSelectElement("/smartSystemMenu/sizer");
            settings.Sizer = sizerElement.Attribute("type") != null && !string.IsNullOrEmpty(sizerElement.Attribute("type").Value) ? (WindowSizerType)int.Parse(sizerElement.Attribute("type").Value) : WindowSizerType.WindowWithMargins;

            var systemTrayIconElement = doreplacedent.XPathSelectElement("/smartSystemMenu/systemTrayIcon");
            if (systemTrayIconElement != null && systemTrayIconElement.Attribute("show") != null && systemTrayIconElement.Attribute("show").Value != null && systemTrayIconElement.Attribute("show").Value.ToLower() == "false")
            {
                settings.ShowSystemTrayIcon = false;
            }

            var languageElement = doreplacedent.XPathSelectElement("/smartSystemMenu/language");
            var languageName = "";
            var languageNameList = new[] { "en", "ru", "zh_cn", "zh_tw", "ja", "ko", "de", "sr", "pt" };
            if (languageElement != null && languageElement.Attribute("name") != null && languageElement.Attribute("name").Value != null)
            {
                languageName = languageElement.Attribute("name").Value.ToLower().Trim();
                settings.LanguageName = languageName;
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "zh-CN"))
            {
                languageName = "zh_cn";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "zh-TW"))
            {
                languageName = "zh_tw";
            }

            if (languageName == "" && Thread.CurrentThread.CurrentCulture.Name == "ja-JP")
            {
                languageName = "ja";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "ko-KR" || Thread.CurrentThread.CurrentCulture.Name == "ko-KP"))
            {
                languageName = "ko";
            }

            if (languageName == "" && Thread.CurrentThread.CurrentCulture.Name == "ru-RU")
            {
                languageName = "ru";
            }

            if (languageName == "" && Thread.CurrentThread.CurrentCulture.Name == "de-DE")
            {
                languageName = "de";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "pt-BR" || Thread.CurrentThread.CurrentCulture.Name == "pt-PT"))
            {
                languageName = "pt";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-BA" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-ME" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-RS" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-CS"))
            {
                languageName = "sr";
            }

            if (languageName == "" || !languageNameList.Contains(languageName))
            {
                languageName = "en";
            }

            var languageItemPath = "/language/items/" + languageName + "/item";
            settings.LanguageSettings.Items = languageDoreplacedent
                .XPathSelectElements(languageItemPath)
                .Select(x => new LanguageItem
                {
                    Name = x.Attribute("name") != null ? x.Attribute("name").Value : "",
                    Value = x.Attribute("value") != null ? x.Attribute("value").Value : "",
                })
                .ToList();

            return settings;
        }

19 Source : ProgramSettings.cs
with MIT License
from AlexanderPro

public static ProgramSettings Read(string fileName)
        {
            var doreplacedent = XDoreplacedent.Load(fileName);
            var settings = new ProgramSettings();
            settings.ListerFormKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key1").Value);
            settings.ListerFormKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key2").Value);
            settings.ListerFormKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key3").Value);
            settings.SearchDialogKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key1").Value);
            settings.SearchDialogKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key2").Value);
            settings.SearchDialogKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key3").Value);
            settings.PrintDialogKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key1").Value);
            settings.PrintDialogKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key2").Value);
            settings.PrintDialogKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key3").Value);
            settings.ListerFormMaximized = bool.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("maximized").Value);
            settings.ListerFormWidth = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("width").Value);
            settings.ListerFormHeight = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("height").Value);
            settings.PluginHighVersion = int.Parse(doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("highVersion").Value);
            settings.PluginLowVersion = int.Parse(doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("lowVersion").Value);
            settings.PluginIniFile = doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("iniFile").Value;
            settings.PluginIniFile = new FileInfo(settings.PluginIniFile).FullName;
            settings.Plugins = doreplacedent.XPathSelectElements("//Settings/Plugins/Plugin").Select(el => new PluginInfo(el.Attribute("path").Value,
                                                                                                                     string.IsNullOrWhiteSpace(el.Attribute("extensions").Value) ? new List<string>() :
                                                                                                                                                                              el.Attribute("extensions").Value.Split(';').ToList())).ToList();
            return settings;
        }

19 Source : IterationManager.cs
with MIT License
from alkampfergit

public IEnumerable<IterationInfo> GetAllIterationsForTeamProject(string teamProjectName)
        {
            var project = _connectionManager.GetTeamProject(teamProjectName);
            NodeInfo[] nodes = _connectionManager
                .CommonStructureService.ListStructures(
                project.Uri.AbsoluteUri);
            var iterationRootNode = nodes.Single(n => n.Name.Equals("iteration", StringComparison.OrdinalIgnoreCase));
            List<IterationInfo> retValue = new List<IterationInfo>();
            var itRoot = _connectionManager
               .CommonStructureService
               .GetNodesXml(new string[] { iterationRootNode.Uri }, true);
            var rootNode = itRoot.FirstChild as XmlElement;
            var xml = rootNode.OuterXml;
            var element = XElement.Parse(xml);
            var xmlNodes = element.Descendants("Node");
            foreach (var node in xmlNodes)
            {
                var path = node.Attribute("Path").Value.Trim('\\', '/');
                var splitted = path.Split('\\');
                var normalizedPath = splitted[0] + "\\" + String.Join("\\", splitted.Skip(2));
                retValue.Add(new IterationInfo()
                {
                    Name = node.Attribute("Name").Value.Trim('\\', '/'),
                    Path = normalizedPath,
                    StartDate = node.Attribute("StartDate")?.Value,
                    EndDate = node.Attribute("FinishDate")?.Value,
                }) ;
            }
            return retValue;
        }

19 Source : bindED.cs
with GNU General Public License v3.0
from alterNERDtive

private static Dictionary<string, List<string>> ReadBinds(string file)
        {
            XElement rootElement;

            rootElement = XElement.Load(file);

            Dictionary<string, List<string>> binds = new Dictionary<string, List<string>>(512);
            if (rootElement != null)
            {
                foreach (XElement c in rootElement.Elements().Where(i => i.Elements().Count() > 0))
                {
                    List<string> keys = new List<string>();
                    foreach (var element in c.Elements().Where(i => i.HasAttributes))
                    {
                        if (element.Name == "Primary")
                        {
                            if (element.Attribute("Device").Value == "Keyboard" && !String.IsNullOrWhiteSpace(element.Attribute("Key").Value) && element.Attribute("Key").Value.StartsWith("Key_"))
                            {
                                foreach (var modifier in element.Elements().Where(i => i.Name.LocalName == "Modifier"))
                                {
                                    keys.Add(modifier.Attribute("Key").Value);
                                }
                                keys.Add(element.Attribute("Key").Value);
                            }
                        }
                        if (keys.Count == 0 && element.Name == "Secondary") //nothing found in primary... look in secondary
                        {
                            if (element.Attribute("Device").Value == "Keyboard" && !String.IsNullOrWhiteSpace(element.Attribute("Key").Value) && element.Attribute("Key").Value.StartsWith("Key_"))
                            {
                                foreach (var modifier in element.Elements().Where(i => i.Name.LocalName == "Modifier"))
                                {
                                    keys.Add(modifier.Attribute("Key").Value);
                                }
                                keys.Add(element.Attribute("Key").Value);
                            }
                        }
                    }
                    binds.Add($"ed{c.Name.LocalName}", keys);
                }
            }
            return binds;
        }

19 Source : CrmWorkflowBase.cs
with MIT License
from AndrewButenko

public Dictionary<string, object> DeserializeDictionary(string dictionaryString)
        {
            var result = new Dictionary<string, object>();

            if (string.IsNullOrEmpty(dictionaryString))
                return result;

            var request = XElement.Parse(dictionaryString);

            request.Elements().ToList().ForEach(e =>
            {
                object fieldValue;

                if (e.Attribute("IsNull")?.Value == "true")
                    fieldValue = null;
                else
                {
                    if (e.Attribute("Type") == null)
                        throw new InvalidPluginExecutionException(
                            $"Attribute {e.Name} is not null and doesn't contain field type, can't deserialize");

                    var typeName = e.Attribute("Type").Value;

                    switch (typeName)
                    {
                        case "System.Boolean":
                            fieldValue = bool.Parse(e.Value);
                            break;
                        case "System.String":
                            fieldValue = e.Value;
                            break;
                        case "System.Int32":
                            fieldValue = int.Parse(e.Value);
                            break;
                        case "System.DateTime":
                            fieldValue = DateTime.Parse(e.Value);
                            break;
                        case "System.Decimal":
                            fieldValue = decimal.Parse(e.Value);
                            break;
                        case "Microsoft.Xrm.Sdk.OptionSetValue":
                            fieldValue = new OptionSetValue(int.Parse(e.Value));
                            break;
                        case "Microsoft.Xrm.Sdk.Money":
                            fieldValue = new Money(decimal.Parse(e.Value));
                            break;
                        case "Microsoft.Xrm.Sdk.EnreplacedyReference":
                            if (e.Element("Id") == null)
                                throw new InvalidPluginExecutionException(
                                    $"Can't parse {e.Name} node with {typeName} type - Id node is not available");

                            if (e.Element("LogicalName") == null)
                                throw new InvalidPluginExecutionException(
                                    $"Can't parse {e.Name} node with {typeName} type - LogicalName node is not available");

                            fieldValue = new EnreplacedyReference(e.Element("LogicalName").Value,
                                new Guid(e.Element("Id").Value));
                            break;
                        default:
                            throw new InvalidPluginExecutionException(
                                $"Serialization is not implemented for {typeName} clreplaced");
                    }

                    result.Add(e.Name.ToString(), fieldValue);
                }
            });

            return result;
        }

19 Source : BaseEngine.cs
with MIT License
from angelsix

protected void ExtractData(FileProcessingData data, FileOutputData output, XDoreplacedent xmlData)
        {
            // Find any variables
            ExtractVariables(data, output, xmlData.Root);

            // Profiles
            foreach (var profileElement in xmlData.Root.Elements("Profile"))
            {
                // Find any variables
                ExtractVariables(data, output, profileElement, profileName: profileElement.Attribute("Name")?.Value);
            }

            // Groups
            foreach (var groupElement in xmlData.Root.Elements("Group"))
            {
                // Find any variables
                ExtractVariables(data, output, groupElement, profileName: groupElement.Attribute("Profile")?.Value, groupName: groupElement.Attribute("Name")?.Value);
            }
        }

19 Source : BaseEngine.cs
with MIT License
from angelsix

protected void ExtractVariables(FileProcessingData data, FileOutputData output, XElement element, string profileName = null, string groupName = null)
        {
            // Loop all elements with the name of variable
            foreach (var variableElement in element.Elements("Variable"))
            {
                try
                {
                    // Create the variable
                    var variable = new EngineVariable
                    {
                        XmlElement = variableElement,
                        Name = variableElement.Attribute("Name")?.Value,
                        ProfileName = variableElement.Attribute("Profile")?.Value ?? profileName,
                        Group = variableElement.Attribute("Group")?.Value ?? groupName,
                        Value = variableElement.Element("Value")?.Value ?? variableElement.Value,
                        Comment = variableElement.Element("Comment")?.Value ?? variableElement.Attribute("Comment")?.Value
                    };

                    // Convert string empty profile names back to null
                    if (variable.ProfileName == string.Empty)
                        variable.ProfileName = null;

                    // If we have no comment, look at previous element for a comment
                    if (string.IsNullOrEmpty(variable.Comment) && variableElement.PreviousNode is XComment)
                        variable.Comment = ((XComment)variableElement.PreviousNode).Value;

                    // Make sure we got a name at least
                    if (string.IsNullOrEmpty(variable.Name))
                    {
                        data.Error = $"Variable has no name {variableElement}";
                        break;
                    }

                    // Add or update variable
                    var existing = output.Variables.FirstOrDefault(f =>
                        f.Name.EqualsIgnoreCase(variable.Name) &&
                        f.ProfileName.EqualsIgnoreCase(variable.ProfileName));

                    // If one exists, update it
                    if (existing != null)
                        existing.Value = variable.Value;
                    // Otherwise, add it
                    else
                        output.Variables.Add(variable);
                }
                catch (Exception ex)
                {
                    data.Error = $"Unexpected error parsing variable {variableElement}. {ex.Message}";

                    // No more processing
                    break;
                }
            }
        }

19 Source : Config.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private static void MigrateConfig(
            string file)
        {
            var buffer = new StringBuilder();
            buffer.Append(File.ReadAllText(file, new UTF8Encoding(false)));

            var xdoc = XDoreplacedent.Parse(buffer.ToString());
            var xelements = xdoc.Root.Elements();

            if (xelements.Any(x => x.Name == nameof(GlobalLogFilters)))
            {
                var filtersParent = xelements
                    .FirstOrDefault(x => x.Name == nameof(GlobalLogFilters));

                var filters = filtersParent.Elements();

                var typeNames = Enum.GetNames(typeof(LogMessageType));

                // 消滅したLogTypeを削除する
                var toRemove = filters
                    .Where(x => !typeNames.Contains(x.Attribute("Key").Value))
                    .ToArray();

                foreach (var e in toRemove)
                {
                    e.Remove();
                }

                // 新しく増えたLogTypeを追加する
                var toAdd = typeNames
                    .Where(x => !filters.Any(y => y.Attribute("Key").Value == x));

                foreach (var key in toAdd)
                {
                    var e = new XElement("Filter");
                    e.SetAttributeValue("Key", key);
                    e.SetAttributeValue("Value", false);
                    filtersParent.Add(e);
                }
            }

            File.WriteAllText(file, xdoc.ToString(), new UTF8Encoding(false));
        }

See More Examples