System.Xml.Linq.XContainer.Element(System.Xml.Linq.XName)

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

1042 Examples 7

19 Source : PathOfBuildingService.cs
with MIT License
from C1rdec

public static bool IsValid(string value)
        {
            var xml = GetXml(value);
            if (string.IsNullOrEmpty(xml))
            {
                return false;
            }

            var doreplacedent = XDoreplacedent.Parse(xml);

            var buildElement = doreplacedent.Root.Element("Build");
            if (buildElement == null)
            {
                return false;
            }

            return true;
        }

19 Source : PathOfBuildingService.cs
with MIT License
from C1rdec

public Build Decode(string buildValue)
        {
            if (this._knownGems == null)
            {
                throw new InvalidOperationException("Must be initialized");
            }

            var build = new Build()
            {
                Value = buildValue,
            };

            var xml = GetXml(buildValue);
            if (string.IsNullOrEmpty(xml))
            {
                return build;
            }

            build.Xml = xml;
            var doreplacedent = XDoreplacedent.Parse(build.Xml);
            var buildElement = doreplacedent.Root.Element("Build");
            if (buildElement != null)
            {
                double totalDps = 0;
                double totalDotDps = 0;

                var totalDpsElement = buildElement.Elements("PlayerStat").FirstOrDefault(e => e.Attribute("stat").Value == "TotalDPS");
                if (totalDpsElement != null)
                {
                    totalDps = (double)totalDpsElement.Attribute("value");
                }

                var totalDotDpsElement = buildElement.Elements("PlayerStat").FirstOrDefault(e => e.Attribute("stat").Value == "TotalDotDPS");
                if (totalDotDpsElement != null)
                {
                    totalDotDps = (double)totalDotDpsElement.Attribute("value");
                }

                build.Damage = new DamageValue()
                {
                    IsDot = totalDotDps > totalDps,
                    Value = totalDotDps > totalDps ? totalDotDps : totalDps,
                };

                var clreplacedAttribute = buildElement.Attribute("clreplacedName");
                if (clreplacedAttribute != null)
                {
                    build.Clreplaced = clreplacedAttribute.Value;
                }

                var ascendancyAttribute = buildElement.Attribute("ascendClreplacedName");
                if (ascendancyAttribute != null)
                {
                    build.Ascendancy = ascendancyAttribute.Value;
                }
            }

            var notesElement = doreplacedent.Root.Element("Notes");
            if (notesElement != null)
            {
                build.Notes = notesElement.Value.Trim();
            }

            var skillsElement = doreplacedent.Root.Element("Skills");
            if (skillsElement != null)
            {
                foreach (var element in skillsElement.Elements())
                {
                    var skill = Skill.FromXml(element, this._knownGems);
                    if (skill.Gems.Any())
                    {
                        build.AddSkill(skill);
                    }
                }
            }

            var treeElement = doreplacedent.Root.Element("Tree");
            if (treeElement != null)
            {
                var urlElement = treeElement.Descendants("URL").OrderByDescending(d => d.Value).FirstOrDefault();
                build.SkillTreeUrl = urlElement.Value.Trim().Replace("preplacedive-skill-tree", "fullscreen-preplacedive-skill-tree");
            }

            var itemsElement = doreplacedent.Root.Element("Items");
            if (itemsElement != null)
            {
                foreach (var element in itemsElement.Elements())
                {
                    var value = element.Value.GetLineAfter("Rarity: ");
                    if (value != null)
                    {
                        var lines = value.Split('\n');
                        var rarity = lines.FirstOrDefault();
                        if (rarity == "UNIQUE" && lines.Length > 2)
                        {
                            var name = lines[1];
                            var uniqueItem = this._knownUniques.FirstOrDefault(u => u.Name == name);
                            if (uniqueItem != null)
                            {
                                build.AddItem(uniqueItem);
                            }
                        }
                    }
                }
            }

            return build;
        }

19 Source : SerializableSetting.cs
with MIT License
from CalciumFramework

void FromXElementCore(XElement element)
		{
			var rootElement = element.Element(elementOptionName) ?? element;

			var version = (int)rootElement.Element(formatVersionElementName);

			Name = (string)rootElement.Element(elementNameName);

			var storageLocationElement = rootElement.Element(elementStorageLocationName);

			if (storageLocationElement != null)
			{
				string storageLocationString = storageLocationElement.Value;
				if (!string.IsNullOrWhiteSpace(storageLocationString))
				{
					StorageLocation parsedValue;
					try
					{
						parsedValue = (StorageLocation)Enum.Parse(typeof(StorageLocation), storageLocationString);
					}
					catch (Exception ex)
					{
						throw new FormatException("StorageLocation element has invalid value of " + storageLocationString, ex);
					}

					StorageLocation = parsedValue;
				}
			}

			var settingValueElement = rootElement.Element(elementValueName);

			if (settingValueElement != null)
			{
				try
				{
					var base64String = settingValueElement.Value;
					byte[] bytes = Convert.FromBase64String(base64String);
					var serializer = Dependency.Resolve<IBinarySerializer, BinarySerializer>();
					object originalObject = serializer.Deserialize<object>(bytes);
					SettingValue = originalObject;
				}
				catch (Exception ex)
				{
					throw new FormatException(elementValueName + " was unable to be parsed from base64 string.", ex);
				}
			}

			if (version > 1)
			{

			}
		}

19 Source : JuniperParser.cs
with Apache License 2.0
from CheckPointSW

private void ParseNat(XElement configNode)
        {
            var nat = configNode.XPathSelectElement("./security/nat");
            if (nat == null)
            {
                return;
            }

            var sourceNat = nat.Element("source");
            if (sourceNat != null)
            {
                var sourceNatPools = sourceNat.Elements("pool");
                foreach (var sourceNatPool in sourceNatPools)
                {
                    var natPool = new Juniper_SourceNatPool();
                    natPool.Parse(sourceNatPool, null);
                    _juniperObjects.Add(natPool);
                }

                var sourceNatPolicies = sourceNat.Elements("rule-set");
                foreach (var sourceNatPolicy in sourceNatPolicies)
                {
                    JuniperObject juniperSourceNatPolicy = new Juniper_SourceNatPolicy();
                    juniperSourceNatPolicy.Parse(sourceNatPolicy, null);
                    _juniperObjects.Add(juniperSourceNatPolicy);

                    var rules = sourceNatPolicy.Elements("rule");
                    foreach (var rule in rules)
                    {
                        var juniperNatRule = new Juniper_SourceNatRule();
                        juniperNatRule.Parse(rule, null);
                        ((Juniper_SourceNatPolicy)juniperSourceNatPolicy).Rules.Add(juniperNatRule);
                    }
                }
            }

            var destinationNat = nat.Element("destination");
            if (destinationNat != null)
            {
                var destinationNatPools = destinationNat.Elements("pool");
                foreach (var destinationNatPool in destinationNatPools)
                {
                    var natPool = new Juniper_DestinationNatPool();
                    natPool.Parse(destinationNatPool, null);
                    _juniperObjects.Add(natPool);
                }

                var destinationNatPolicies = destinationNat.Elements("rule-set");
                foreach (var destinationNatPolicy in destinationNatPolicies)
                {
                    JuniperObject juniperDestinationNatPolicy = new Juniper_DestinationNatPolicy();
                    juniperDestinationNatPolicy.Parse(destinationNatPolicy, null);
                    _juniperObjects.Add(juniperDestinationNatPolicy);

                    var rules = destinationNatPolicy.Elements("rule");
                    foreach (var rule in rules)
                    {
                        var juniperNatRule = new Juniper_DestinationNatRule();
                        juniperNatRule.Parse(rule, null);
                        ((Juniper_DestinationNatPolicy)juniperDestinationNatPolicy).Rules.Add(juniperNatRule);
                    }
                }
            }

            var staticNat = nat.Element("static");
            if (staticNat != null)
            {
                var staticNatPolicies = staticNat.Elements("rule-set");
                foreach (var staticNatPolicy in staticNatPolicies)
                {
                    JuniperObject juniperStaticNatPolicy = new Juniper_StaticNatPolicy();
                    juniperStaticNatPolicy.Parse(staticNatPolicy, null);
                    _juniperObjects.Add(juniperStaticNatPolicy);

                    var rules = staticNatPolicy.Elements("rule");
                    foreach (var rule in rules)
                    {
                        var juniperNatRule = new Juniper_StaticNatRule();
                        juniperNatRule.Parse(rule, null);
                        ((Juniper_StaticNatPolicy)juniperStaticNatPolicy).Rules.Add(juniperNatRule);
                    }
                }
            }
        }

19 Source : JuniperParser.cs
with Apache License 2.0
from CheckPointSW

private XElement LoadConfig(string filename)
        {
            var configDoc = XDoreplacedent.Load(filename, LoadOptions.SetLineInfo);
            if (configDoc.Root == null)
            {
                throw new InvalidDataException("Invalid XML structure: XML root element is missing.");
            }

            var configNode = configDoc.Root.Element("configuration");
            if (configNode == null)
            {
                throw new InvalidDataException("Invalid XML structure: 'configuration' element is missing.");
            }

            return configNode;
        }

19 Source : JuniperParser.cs
with Apache License 2.0
from CheckPointSW

protected override void ParseVersion(object versionProvider)
        {
            var configNode = (XElement)versionProvider;
            if (configNode != null)
            {
                var versionNode = configNode.Element("version");
                if (versionNode != null && versionNode.Value.Length > 0)
                {
                    VendorVersion = Regex.Match(versionNode.Value, @"\d+(\.\d+)?").Value;
                }
            }
        }

19 Source : JuniperParser.cs
with Apache License 2.0
from CheckPointSW

private bool ParseAddressBooks(XElement configNode)
        {
            var addressBooks = configNode.XPathSelectElements("./security/address-book");
            if (!addressBooks.Any())
            {
                return false;
            }

            foreach (var addressBook in addressBooks)
            {
                string addressBookName = JuniperObject.GlobalZoneName;
                string addressBookZone = JuniperObject.GlobalZoneName;

                var addressBookNameNode = addressBook.Element("name");
                if (addressBookNameNode != null && !string.IsNullOrEmpty(addressBookNameNode.Value))
                {
                    addressBookName = addressBookNameNode.Value;
                }

                var zoneNameNode = addressBook.XPathSelectElement("./attach/zone/name");
                if (zoneNameNode != null && !string.IsNullOrEmpty(zoneNameNode.Value))
                {
                    addressBookZone = zoneNameNode.Value;
                }
                else if (addressBookName != JuniperObject.GlobalZoneName)
                {
                    // Found non global address-book without a zone attached!!!
                    continue;
                }

                var addresses = addressBook.Elements("address");
                ParseAddresses(addresses, addressBookZone);

                var addressGroups = addressBook.Elements("address-set");
                foreach (var group in addressGroups)
                {
                    JuniperObject juniperAddressGroup = new Juniper_AddressGroup();
                    juniperAddressGroup.Parse(group, addressBookZone);
                    _juniperObjects.Add(juniperAddressGroup);

                    HandleDuplicatedAddressName(juniperAddressGroup.Name, addressBookZone);
                }
            }

            return true;
        }

19 Source : JuniperParser.cs
with Apache License 2.0
from CheckPointSW

private void ParseAddresses(IEnumerable<XElement> addresses, string zoneName)
        {
            foreach (var address in addresses)
            {
                var dnsName = address.Element("dns-name");
                var ipPrefix = address.Element("ip-prefix");
                var rengeAddress = address.Element("range-address");

                JuniperObject juniperObject = null;

                if (dnsName != null)
                {
                    juniperObject = new Juniper_Fqdn();
                }
                else if (ipPrefix != null)
                {
                    if (IsHostObject(ipPrefix.Value))
                    {
                        juniperObject = new Juniper_Host();
                    }
                    else
                    {
                        juniperObject = new Juniper_Network();
                    }
                }
                else if (rengeAddress != null)
                {
                    juniperObject = new Juniper_Range();
                }

                if (juniperObject != null)
                {
                    juniperObject.Parse(address, zoneName);
                    _juniperObjects.Add(juniperObject);

                    HandleDuplicatedAddressName(juniperObject.Name, zoneName);
                }
            }
        }

19 Source : JuniperParser.cs
with Apache License 2.0
from CheckPointSW

private void ParsePolicy(XElement configNode)
        {
            // First, parse the zone based policy.
            var zonePolicies = configNode.XPathSelectElements("./security/policies/policy");
            foreach (var zonePolicy in zonePolicies)
            {
                JuniperObject juniperZonePolicy = new Juniper_ZonePolicy();
                juniperZonePolicy.Parse(zonePolicy, null);
                _juniperObjects.Add(juniperZonePolicy);

                var policies = zonePolicy.Elements("policy");
                foreach (var policy in policies)
                {
                    var juniperRule = new Juniper_PolicyRule();
                    juniperRule.Parse(policy, null);
                    ((Juniper_ZonePolicy)juniperZonePolicy).Rules.Add(juniperRule);
                }
            }

            // Then, parse the global policy.
            var globalPolicies = configNode.XPathSelectElements("./security/policies/global/policy");
            foreach (var globalPolicy in globalPolicies)
            {
                var juniperGlobalRule = new Juniper_GlobalPolicyRule();
                juniperGlobalRule.Parse(globalPolicy, null);
                _juniperGlobalPolicyRules.Add(juniperGlobalRule);
            }

            // Resolve the policy default action.
            var defaultAction = Juniper_PolicyRule.ActionType.Deny;
            var policyDefaultAction = configNode.XPathSelectElement("./security/policies/default-policy");
            if (policyDefaultAction != null && policyDefaultAction.Element("permit-all") != null)
            {
                defaultAction = Juniper_PolicyRule.ActionType.Permit;
            }

            // Append the policy default action as a global rule!!!
            var juniperDefaultActionRule = new Juniper_GlobalPolicyRule();
            juniperDefaultActionRule.GenerateDefaultActionRule(defaultAction);
            _juniperGlobalPolicyRules.Add(juniperDefaultActionRule);
        }

19 Source : UpdateHelper.cs
with Apache License 2.0
from Chem4Word

public static bool FetchUpdateInfo()
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            bool updateRequired = false;

            Globals.Chem4WordV3.VersionsBehind = 0;

            var replacedembly = replacedembly.GetExecutingreplacedembly();

            ReadThisVersion(replacedembly);
            if (Globals.Chem4WordV3.ThisVersion != null)
            {
                string currentVersionNumber = Globals.Chem4WordV3.ThisVersion.Root.Element("Number").Value;
                DateTime currentReleaseDate = SafeDate.Parse(Globals.Chem4WordV3.ThisVersion.Root.Element("Released").Value);
                Debug.WriteLine("Current Version " + currentVersionNumber + " Released " + SafeDate.ToShortDate(currentReleaseDate));

                string xml = GetVersionsXmlFile();
                if (!string.IsNullOrEmpty(xml))
                {
                    #region Got Our File

                    Globals.Chem4WordV3.AllVersions = XDoreplacedent.Parse(xml);
                    var versions = Globals.Chem4WordV3.AllVersions.XPathSelectElements("//Version");
                    foreach (var version in versions)
                    {
                        var thisVersionNumber = version.Element("Number").Value;
                        DateTime thisVersionDate = SafeDate.Parse(version.Element("Released").Value);
                        Debug.WriteLine("New Version " + thisVersionNumber + " Released " + SafeDate.ToShortDate(thisVersionDate));
                        if (thisVersionDate > currentReleaseDate)
                        {
                            Globals.Chem4WordV3.VersionsBehind++;
                            updateRequired = true;
                        }
                    }

                    // Save VersionsBehind and Last Checked for next start up
                    Debug.WriteLine($"Saving Versions Behind in Registry: {Globals.Chem4WordV3.VersionsBehind}");
                    RegistryKey key = Registry.CurrentUser.CreateSubKey(Constants.Chem4WordRegistryKey);
                    key?.SetValue(Constants.RegistryValueNameVersionsBehind, Globals.Chem4WordV3.VersionsBehind.ToString());

                    #endregion Got Our File
                }
            }
            else
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Error", "Failed to parse resource 'Data.This-Version.xml'");
            }

            return updateRequired;
        }

19 Source : AutomaticUpdate.cs
with Apache License 2.0
from Chem4Word

private void AutomaticUpdate_Load(object sender, EventArgs e)
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";
            try
            {
                if (TopLeft.X != 0 && TopLeft.Y != 0)
                {
                    Left = (int)TopLeft.X;
                    Top = (int)TopLeft.Y;
                }

                string currentVersionNumber = CurrentVersion.Root.Element("Number").Value;
                DateTime currentReleaseDate = SafeDate.Parse(CurrentVersion.Root.Element("Released").Value);

                lblInfo.Text = "Your current version of Chem4Word is " + currentVersionNumber + "; Released " + currentReleaseDate.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);
                _telemetry.Write(module, "AutomaticUpdate", lblInfo.Text);

                var versions = NewVersions.XPathSelectElements("//Version");
                foreach (var version in versions)
                {
                    if (string.IsNullOrEmpty(_downloadUrl))
                    {
                        _downloadUrl = version.Element("Url").Value;
                    }

                    var thisVersionNumber = version.Element("Number").Value;
                    DateTime thisVersionDate = SafeDate.Parse(version.Element("Released").Value);

                    if (currentReleaseDate >= thisVersionDate)
                    {
                        break;
                    }

                    AddHeaderLine("Version " + thisVersionNumber + "; Released " + thisVersionDate.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture), Color.Blue);
                    var changes = version.XPathSelectElements("Changes/Change");
                    foreach (var change in changes)
                    {
                        if (change.Value.StartsWith("Note:"))
                        {
                            AddBullereplacedem(change.Value.Remove(0, 6), Color.Red);
                        }
                        else
                        {
                            AddBullereplacedem(change.Value, Color.Black);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new ReportError(_telemetry, TopLeft, module, ex).ShowDialog();
            }
        }

19 Source : Setup.cs
with Apache License 2.0
from Chem4Word

private void Setup_Load(object sender, EventArgs e)
        {
            // Move up and left by half the form size
            Left = Left - Width / 2;
            Top = Top - Height / 2;

            Show();
            Application.DoEvents();

            bool isDesignTimeInstalled = false;
            bool isRuntimeInstalled = false;
            bool isWordInstalled = false;
            bool isOperatingSystemWindows7Plus = false;
            bool isChem4WordVersion2Installed = false;
            bool isChem4WordVersion3Installed = false;

            #region Detect Windows Version

            OperatingSystem osVer = Environment.OSVersion;
            // Check that OsVerion is greater or equal to 6.1
            if (osVer.Version.Major >= 6 && osVer.Version.Minor >= 1)
            {
                // Running Windows 7 or Windows 2008 R2
                isOperatingSystemWindows7Plus = true;
            }

            #endregion Detect Windows Version

            WindowsInstalled.Indicator = isOperatingSystemWindows7Plus ? Properties.Resources.Windows : Properties.Resources.Halt;
            Application.DoEvents();

            #region Detect Word

            isWordInstalled = OfficeHelper.GetWinWordVersionNumber() >= 2010;

            #endregion Detect Word

            WordInstalled.Indicator = isWordInstalled ? Properties.Resources.Word : Properties.Resources.Halt;
            Application.DoEvents();

            #region .Net Framework

            // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
            // Not sure if this can be done as this is a .Net 4.5.2 app !

            #endregion .Net Framework

            #region Detect Design Time VSTO

            string feature = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSTO_DT\VS10\Feature");
            if (!string.IsNullOrEmpty(feature))
            {
                isDesignTimeInstalled = true;
            }

            #endregion Detect Design Time VSTO

            #region Detect Runtime VSTO

            string version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSTO Runtime Setup\v4R", "Version");
            if (string.IsNullOrEmpty(version))
            {
                version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VSTO Runtime Setup\v4R", "Version");
            }

            Version mimimumVersion = new Version("10.0.60724");
            int result = -2;

            if (!string.IsNullOrEmpty(version))
            {
                Version installedVersion = new Version(version);
                result = installedVersion.CompareTo(mimimumVersion);

                if (result >= 0)
                {
                    isRuntimeInstalled = true;
                }
            }

            // SOFTWARE\Microsoft\VSTO_DT\VS10\Feature
            if (!isRuntimeInstalled)
            {
                version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSTO_DT\VS10\Feature");

                if (string.IsNullOrEmpty(version))
                {
                    version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VSTO_DT\VS10\Feature");
                }

                if (!string.IsNullOrEmpty(version))
                {
                    isRuntimeInstalled = true;
                }
            }

            #endregion Detect Runtime VSTO

            if (isDesignTimeInstalled || isRuntimeInstalled)
            {
                VstoInstalled.Indicator = Properties.Resources.Yes;
                _state = State.DownloadChem4Word;
            }
            else
            {
                VstoInstalled.Indicator = Properties.Resources.Waiting;
                _state = State.DownloadVsto;
            }
            Application.DoEvents();

            #region Is Chem4Word Installed

            isChem4WordVersion2Installed = FindOldVersion();
            //isChem4WordVersion3Installed = FindCurrentVersion();

            #endregion Is Chem4Word Installed

            if (isOperatingSystemWindows7Plus && isWordInstalled)
            {
                if (isChem4WordVersion2Installed)
                {
                    RegistryHelper.WriteAction("Old Version of Chem4Word detected");
                    AddInInstalled.Indicator = Properties.Resources.Halt;
                    AddInInstalled.Description = "Version 2 of Chem4Word detected";
                    Information.Text = "A previous version of Chem4Word has been detected, please uninstall it.";
                    Action.Text = "Cancel";
                }
                else if (isChem4WordVersion3Installed)
                {
                    RegistryHelper.WriteAction("Version 3 of Chem4Word detected");
                    AddInInstalled.Indicator = Properties.Resources.Yes;
                    AddInInstalled.Description = "Version 3 of Chem4Word detected";
                    Information.Text = "Nothing to do.";
                    Action.Text = "Cancel";
                }
                else
                {
                    AddInInstalled.Indicator = Properties.Resources.Waiting;
                    Application.DoEvents();

                    RegistryHelper.WriteAction("Downloading Chem4Word-Versions.xml");
                    var xml = GetVersionsXmlFile();
                    if (!string.IsNullOrEmpty(xml))
                    {
                        var x = XDoreplacedent.Parse(xml);
                        var versions = x.XPathSelectElements("//Version");
                        foreach (var element in versions)
                        {
                            if (string.IsNullOrEmpty(_latestVersion))
                            {
                                _latestVersion = element.Element("Url")?.Value;
                                RegistryHelper.WriteAction($"Latest version is {_latestVersion}");
                            }
                            break;
                        }
                    }

                    // Default to Specific Beta
                    if (string.IsNullOrEmpty(_latestVersion))
                    {
                        _latestVersion = ChangeDomain(DefaultMsiFile);
                        RegistryHelper.WriteAction($"Defaulting to {_latestVersion}");
                    }
                }
            }
            else
            {
                if (!isWordInstalled)
                {
                    WordInstalled.Indicator = Properties.Resources.No;
                    Information.Text = "Please install Microsoft Word 2010 or 2013 or 2016.";
                }

                if (!isOperatingSystemWindows7Plus)
                {
                    WindowsInstalled.Indicator = Properties.Resources.No;
                    Information.Text = "This program requires Windows 7 or greater.";
                }

                VstoInstalled.Indicator = Properties.Resources.Halt;
                AddInInstalled.Indicator = Properties.Resources.Halt;

                Action.Text = "Cancel";
            }
        }

19 Source : UpdateHelper.cs
with Apache License 2.0
from Chem4Word

public static bool FetchUpdateInfo()
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            bool updateRequired = false;

            Globals.Chem4WordV3.VersionsBehind = 0;

            var replacedembly = replacedembly.GetExecutingreplacedembly();

            ReadThisVersion(replacedembly);
            if (Globals.Chem4WordV3.ThisVersion != null)
            {
                DateTime currentReleaseDate = SafeDate.Parse(Globals.Chem4WordV3.ThisVersion.Root.Element("Released").Value);

                string xml = GetVersionsXmlFile();
                if (!string.IsNullOrEmpty(xml))
                {
                    #region Got Our File

                    Globals.Chem4WordV3.AllVersions = XDoreplacedent.Parse(xml);
                    RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(Constants.Chem4WordRegistryKey);

                    var expires = Globals.Chem4WordV3.AllVersions.XPathSelectElements("//EndOfLife").FirstOrDefault();
                    if (expires != null)
                    {
                        var expiryDate = SafeDate.Parse(expires.Value);
                        if (DateTime.Now.ToUniversalTime() > expiryDate)
                        {
                            Globals.Chem4WordV3.IsEndOfLife = true;
                            registryKey?.SetValue(Constants.RegistryValueNameEndOfLife, "true");
                        }
                    }

                    var versions = Globals.Chem4WordV3.AllVersions.XPathSelectElements("//Version");
                    bool mostRecent = true;
                    foreach (var version in versions)
                    {
                        var thisVersionNumber = version.Element("Number")?.Value;
                        DateTime thisVersionDate = SafeDate.Parse(version.Element("Released")?.Value);
    
                        if (thisVersionDate > currentReleaseDate)
                        {
                            Globals.Chem4WordV3.VersionsBehind++;
                            updateRequired = true;
                        }

                        if (mostRecent)
                        {
                            Globals.Chem4WordV3.VersionAvailable = thisVersionNumber;
                            registryKey?.SetValue(Constants.RegistryValueNameAvailableVersion, thisVersionNumber);

                            var isBeta = version.Element("IsBeta")?.Value;
                            Globals.Chem4WordV3.VersionAvailableIsBeta = bool.Parse(isBeta);
                            registryKey?.SetValue(Constants.RegistryValueNameAvailableIsBeta, isBeta);

                            mostRecent = false;
                        }
                    }

                    // Save VersionsBehind and Last Checked for next start up
                    Debug.WriteLine($"Saving Versions Behind in Registry: {Globals.Chem4WordV3.VersionsBehind}");
                    registryKey?.SetValue(Constants.RegistryValueNameVersionsBehind, Globals.Chem4WordV3.VersionsBehind.ToString());

                    #endregion Got Our File
                }
            }
            else
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Error", "Failed to parse resource 'Data.This-Version.xml'");
            }

            return updateRequired;
        }

19 Source : AutomaticUpdate.cs
with Apache License 2.0
from Chem4Word

private void AutomaticUpdate_Load(object sender, EventArgs e)
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";
            try
            {
                using (new WaitCursor())
                {
                    if (!PointHelper.PointIsEmpty(TopLeft))
                    {
                        Left = (int)TopLeft.X;
                        Top = (int)TopLeft.Y;
                    }

                    string currentVersionNumber = CurrentVersion.Root.Element("Number").Value;
                    DateTime currentReleaseDate = SafeDate.Parse(CurrentVersion.Root.Element("Released").Value);

                    lblInfo.Text = "Your current version of Chem4Word is " + currentVersionNumber + "; Released " + SafeDate.ToShortDate(currentReleaseDate);
                    _telemetry.Write(module, "AutomaticUpdate", lblInfo.Text);

                    var versions = NewVersions.XPathSelectElements("//Version");
                    foreach (var version in versions)
                    {
                        if (string.IsNullOrEmpty(_downloadUrl))
                        {
                            _downloadUrl = version.Element("Url").Value;
                        }

                        var thisVersionNumber = version.Element("Number").Value;
                        DateTime thisVersionDate = SafeDate.Parse(version.Element("Released").Value);

                        if (currentReleaseDate >= thisVersionDate)
                        {
                            break;
                        }

                        AddHeaderLine("Version " + thisVersionNumber + "; Released " + SafeDate.ToShortDate(thisVersionDate), Color.Blue);
                        var changes = version.XPathSelectElements("Changes/Change");
                        foreach (var change in changes)
                        {
                            if (change.Value.StartsWith("Note:"))
                            {
                                AddBullereplacedem(change.Value.Remove(0, 6), Color.Red);
                            }
                            else
                            {
                                AddBullereplacedem(change.Value, Color.Black);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new ReportError(_telemetry, TopLeft, module, ex).ShowDialog();
            }
        }

19 Source : Setup.cs
with Apache License 2.0
from Chem4Word

private void Setup_Load(object sender, EventArgs e)
        {
            // Move up and left by half the form size
            Left = Left - Width / 2;
            Top = Top - Height / 2;

            Show();
            Application.DoEvents();

            bool isDesignTimeInstalled = false;
            bool isRuntimeInstalled = false;
            bool isOperatingSystemWindows7Plus = false;
            bool isChem4WordVersion3Installed = false;

            #region Detect Windows Version

            OperatingSystem osVer = Environment.OSVersion;
            // Check that OsVerion is greater or equal to 6.1
            if (osVer.Version.Major >= 6 && osVer.Version.Minor >= 1)
            {
                // Running Windows 7 or Windows 2008 R2
                isOperatingSystemWindows7Plus = true;
            }

            #endregion Detect Windows Version

            WindowsInstalled.Indicator = isOperatingSystemWindows7Plus ? Properties.Resources.Windows : Properties.Resources.Halt;
            Application.DoEvents();

            #region Detect Word

            bool isWordInstalled = OfficeHelper.GetWinWordVersionNumber() >= 2010;

            #endregion Detect Word

            WordInstalled.Indicator = isWordInstalled ? Properties.Resources.Word : Properties.Resources.Halt;
            Application.DoEvents();

            #region .Net Framework

            // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
            // Not sure if this can be done as this is a .Net 4.5.2 app !

            #endregion .Net Framework

            #region Detect Design Time VSTO

            string feature = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSTO_DT\VS10\Feature");
            if (!string.IsNullOrEmpty(feature))
            {
                isDesignTimeInstalled = true;
            }

            #endregion Detect Design Time VSTO

            #region Detect Runtime VSTO

            string version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSTO Runtime Setup\v4R", "Version");
            if (string.IsNullOrEmpty(version))
            {
                version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VSTO Runtime Setup\v4R", "Version");
            }

            Version mimimumVersion = new Version("10.0.60724");
            int result = -2;

            if (!string.IsNullOrEmpty(version))
            {
                Version installedVersion = new Version(version);
                result = installedVersion.CompareTo(mimimumVersion);

                if (result >= 0)
                {
                    isRuntimeInstalled = true;
                }
            }

            // SOFTWARE\Microsoft\VSTO_DT\VS10\Feature
            if (!isRuntimeInstalled)
            {
                version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSTO_DT\VS10\Feature");

                if (string.IsNullOrEmpty(version))
                {
                    version = GetRegistryValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VSTO_DT\VS10\Feature");
                }

                if (!string.IsNullOrEmpty(version))
                {
                    isRuntimeInstalled = true;
                }
            }

            #endregion Detect Runtime VSTO

            if (isDesignTimeInstalled || isRuntimeInstalled)
            {
                VstoInstalled.Indicator = Properties.Resources.Yes;
                _state = State.DownloadChem4Word;
            }
            else
            {
                VstoInstalled.Indicator = Properties.Resources.Waiting;
                _state = State.DownloadVsto;
            }
            Application.DoEvents();

            #region Is Chem4Word Installed

            bool isChem4WordVersion2Installed = FindOldVersion();

            #endregion Is Chem4Word Installed

            if (isOperatingSystemWindows7Plus && isWordInstalled)
            {
                if (isChem4WordVersion2Installed)
                {
                    RegistryHelper.WriteAction("Old Version of Chem4Word detected");
                    AddInInstalled.Indicator = Properties.Resources.Halt;
                    AddInInstalled.Description = "Version 2 of Chem4Word detected";
                    Information.Text = "A previous version of Chem4Word has been detected, please uninstall it.";
                    Action.Text = "Cancel";
                }
                else if (isChem4WordVersion3Installed)
                {
                    RegistryHelper.WriteAction("Version 3 of Chem4Word detected");
                    AddInInstalled.Indicator = Properties.Resources.Yes;
                    AddInInstalled.Description = "Version 3 of Chem4Word detected";
                    Information.Text = "Nothing to do.";
                    Action.Text = "Cancel";
                }
                else
                {
                    AddInInstalled.Indicator = Properties.Resources.Waiting;
                    Application.DoEvents();

                    RegistryHelper.WriteAction("Downloading Chem4Word-Versions.xml");
                    var xml = GetVersionsXmlFile();
                    if (!string.IsNullOrEmpty(xml))
                    {
                        var x = XDoreplacedent.Parse(xml);
                        var versions = x.XPathSelectElements("//Version");
                        foreach (var element in versions)
                        {
                            if (string.IsNullOrEmpty(_latestVersion))
                            {
                                _latestVersion = element.Element("Url")?.Value;
                                RegistryHelper.WriteAction($"Latest version is {_latestVersion}");
                            }
                            break;
                        }
                    }

                    // Default to Specific Beta
                    if (string.IsNullOrEmpty(_latestVersion))
                    {
                        _latestVersion = ChangeDomain(DefaultMsiFile);
                        RegistryHelper.WriteAction($"Defaulting to {_latestVersion}");
                    }
                }
            }
            else
            {
                if (!isWordInstalled)
                {
                    WordInstalled.Indicator = Properties.Resources.No;
                    Information.Text = "Please install Microsoft Word 2010 or 2013 or 2016.";
                }

                if (!isOperatingSystemWindows7Plus)
                {
                    WindowsInstalled.Indicator = Properties.Resources.No;
                    Information.Text = "This program requires Windows 7 or greater.";
                }

                VstoInstalled.Indicator = Properties.Resources.Halt;
                AddInInstalled.Indicator = Properties.Resources.Halt;

                Action.Text = "Cancel";
            }
        }

19 Source : ProjectFileUpdater.cs
with GNU General Public License v3.0
from christianhelle

public XDoreplacedent UpdatePropertyGroup(IReadOnlyDictionary<string, string> properties)
        {
            var propertyGroups = xml
                .Elements("Project")
                .Elements("PropertyGroup")
                .Elements()
                .ToList();

            foreach (var property in properties)
            {
                if (propertyGroups.All(c => c.Name != property.Key))
                {
                    propertyGroups.Add(
                        new XElement(property.Key, property.Value));
                }
                else
                {
                    propertyGroups
                        .First(c => c.Name == property.Key)
                        .Value = property.Value.ToString();
                }
            }

            xml.Root?.Element("PropertyGroup")?.ReplaceNodes(propertyGroups);

            if (file != null)
                xml.Save(file);

            return xml;
        }

19 Source : FixRedirectsCommandPackage.cs
with MIT License
from CloudNimble

private async Task FixBindingRedirectsAsync()
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            _isProcessing = true;

            var files = ProjectHelpers.GetSelectedItemPaths().Where(c => c.ToLower().EndsWith("web.config") || c.ToLower().EndsWith("app.config"));

            if (!files.Any())
            {
                _dte.StatusBar.Text = "Please select a web.config or app.config file to fix.";
                _isProcessing = false;
                return;
            }

            //var projectFolder = ProjectHelpers.GetRootFolder(ProjectHelpers.GetActiveProject());
            int count = files.Count();

            //RWM: Don't mess with these.
            XNamespace defaultNs = "";
            XNamespace replacedemblyBindingNs = "urn:schemas-microsoft-com:asm.v1";
            var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };

            try
            {
                string text = count == 1 ? " file" : " files";
                _dte.StatusBar.Progress(true, $"Fixing {count} config {text}...", AmountCompleted: 1, Total: count + 1);

                foreach (var file in files)
                {
                    var replacedemblyBindings = new XElement(replacedemblyBindingNs + "replacedemblyBinding");
                    var newBindings = new SortedDictionary<string, XElement>();

                    //RWM: Start by backing up the files.
                    File.Copy(file, file + ".bak", true);
                    Logger.Log($"Backup created for {file}.");

                    //RWM: Load the files.
                    var config = XDoreplacedent.Load(file);

                    var oldBindingRoot = config.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "replacedemblyBinding");
                    var oldCount = oldBindingRoot.Elements().Count();

                    foreach (var dependentreplacedembly in oldBindingRoot.Elements().ToList())
                    {
                        var replacedemblyIdenreplacedy = dependentreplacedembly.Element(replacedemblyBindingNs + "replacedemblyIdenreplacedy");
                        var bindingRedirect = dependentreplacedembly.Element(replacedemblyBindingNs + "bindingRedirect");

                        if (newBindings.ContainsKey(replacedemblyIdenreplacedy.Attribute("name").Value))
                        {
                            Logger.Log($"Reference already exists for {replacedemblyIdenreplacedy.Attribute("name").Value}. Checking version...");
                            //RWM: We've seen this replacedembly before. Check to see if we can update the version.
                            var newBindingRedirect = newBindings[replacedemblyIdenreplacedy.Attribute("name").Value].Descendants(replacedemblyBindingNs + "bindingRedirect").FirstOrDefault();
                            if (newBindingRedirect == null)
                            {
                                Logger.Log($"The bindingRedirect tag for {replacedemblyIdenreplacedy.Attribute("name").Value} was not found. Skipping.");
                                continue;
                            }

                            var oldVersion = Version.Parse(newBindingRedirect.Attribute("newVersion").Value);
                            var newVersion = Version.Parse(bindingRedirect.Attribute("newVersion").Value);

                            if (newVersion > oldVersion)
                            {
                                newBindingRedirect.ReplaceWith(bindingRedirect);
                                Logger.Log($"Version was newer. Binding updated.");
                            }
                            else
                            {
                                Logger.Log($"Version was the same or older. No update needed. Skipping.");
                            }
                        }
                        else
                        {
                            newBindings.Add(replacedemblyIdenreplacedy.Attribute("name").Value, dependentreplacedembly);
                        }
                    }

                    //RWM: Add the SortedDictionary items to our new replacedemblyBinding element.
                    foreach (var binding in newBindings)
                    {
                        replacedemblyBindings.Add(binding.Value);
                    }

                    //RWM: Fix up the web.config by adding the new replacedemblyBindings and removing the old one.
                    oldBindingRoot.AddBeforeSelf(replacedemblyBindings);
                    oldBindingRoot.Remove();

                    //RWM: Save the config file.
                    ProjectHelpers.CheckFileOutOfSourceControl(file);
                    config.Save(file);

                    Logger.Log($"Update complete. Result: {oldCount} bindings before, {newBindings.Count} after.");
                }
            }
            catch (AggregateException agEx)
            {
                _dte.StatusBar.Progress(false);
                Logger.Log($"Update failed. Exceptions:");
                foreach (var ex in agEx.InnerExceptions)
                {
                    Logger.Log($"Message: {ex.Message}{Environment.NewLine}{ex.StackTrace}");
                }
                _dte.StatusBar.Text = "Operation failed. Please see Output Window for details.";
                _isProcessing = false;

            }
            finally
            {
                _dte.StatusBar.Progress(false);
                _dte.StatusBar.Text = "Operation finished. Please see Output Window for details.";
                _isProcessing = false;
            }

        }

19 Source : Converter.cs
with Apache License 2.0
from cognidox

private static bool IsOpenXMLReadOnlyEnforced(string filename)
        {
            // Read an OpenXML type doreplacedent
            using (Package package = Package.Open(path: filename, packageMode: FileMode.Open, packageAccess: FileAccess.Read))
            {
                if (null == package)
                {
                    return false;
                }
                try
                {
                    // Doreplacedent security is set in the extended properties
                    // https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/cc845474(v%3doffice.14)
                    string extendedType = "http://schemas.openxmlformats.org/officeDoreplacedent/2006/relationships/extended-properties";
                    PackageRelationshipCollection extendedProps = package.GetRelationshipsByType(extendedType);
                    if (null != extendedProps)
                    {
                        IEnumerator extendedPropsList = extendedProps.GetEnumerator();
                        if (extendedPropsList.MoveNext())
                        {
                            Uri extendedPropsUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), ((PackageRelationship)extendedPropsList.Current).TargetUri);
                            PackagePart props = package.GetPart(extendedPropsUri);
                            if (null != props)
                            {
                                // Read the internal docProps/app.xml XML file
                                XDoreplacedent xmlDoc = XDoreplacedent.Load(props.GetStream());
                                XElement securityEl = xmlDoc.Root.Element(XName.Get("DocSecurity", xmlDoc.Root.GetDefaultNamespace().NamespaceName));
                                if (null != securityEl)
                                {
                                    if (!String.IsNullOrWhiteSpace(securityEl.Value))
                                    {
                                        // See https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/cc840043%28v%3doffice.14%29
                                        return ((Int16.Parse(securityEl.Value) & 4) == 4);
                                    }
                                }

                                package.Close();
                                // PowerPoint doesn't use DocSecurity (*sigh*) so need another check
                                XElement appEl = xmlDoc.Root.Element(XName.Get("Application", xmlDoc.Root.GetDefaultNamespace().NamespaceName));
                                if (null != appEl)
                                {
                                    if (!String.IsNullOrWhiteSpace(appEl.Value) &&
                                        appEl.Value.IndexOf("PowerPoint", StringComparison.InvariantCultureIgnoreCase) >= 0)
                                    {
                                        PresentationDoreplacedent presentationDoreplacedent = PresentationDoreplacedent.Open(path: filename, isEditable: false);
                                        if (null != presentationDoreplacedent &&
                                            presentationDoreplacedent.PresentationPart.Presentation.ModificationVerifier != null) {
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception) { }
                return false;
            }
        }

19 Source : DynamicJson.cs
with GNU General Public License v3.0
from CommentViewerCollection

public bool IsDefined(string name)
        {
            return IsObject && (xml.Element(name) != null);
        }

19 Source : DynamicJson.cs
with GNU General Public License v3.0
from CommentViewerCollection

public bool Delete(string name)
        {
            var elem = xml.Element(name);
            if (elem != null)
            {
                elem.Remove();
                return true;
            }
            else return false;
        }

19 Source : DynamicJson.cs
with GNU General Public License v3.0
from CommentViewerCollection

public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            return (IsArray)
                ? TryGet(xml.Elements().ElementAtOrDefault((int)indexes[0]), out result)
                : TryGet(xml.Element((string)indexes[0]), out result);
        }

19 Source : DynamicJson.cs
with GNU General Public License v3.0
from CommentViewerCollection

public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return (IsArray)
                ? TryGet(xml.Elements().ElementAtOrDefault(int.Parse(binder.Name)), out result)
                : TryGet(xml.Element(binder.Name), out result);
        }

19 Source : DynamicJson.cs
with GNU General Public License v3.0
from CommentViewerCollection

private bool TrySet(string name, object value)
        {
            var type = GetJsonType(value);
            var element = xml.Element(name);
            if (element == null)
            {
                xml.Add(new XElement(name, CreateTypeAttr(type), CreateJsonNode(value)));
            }
            else
            {
                element.Attribute("type").Value = type.ToString();
                element.ReplaceNodes(CreateJsonNode(value));
            }

            return true;
        }

19 Source : DynamicXmlParser.cs
with GNU General Public License v3.0
from CommentViewerCollection

public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_element == null)
            {
                result = null;
                return false;
            }

            var child = _element.Element(binder.Name);
            if (child == null)
            {
                result = null;
                return false;
            }
            else
            {
                result = new DynamicXmlParser(child);
                return true;
            }
        }

19 Source : DynamicXmlParser.cs
with GNU General Public License v3.0
from CommentViewerCollection

public bool HasElement(string name)
        {
            var s = _element.Element(name);
            return (s != null);
        }

19 Source : DynamicXmlParser.cs
with GNU General Public License v3.0
from CommentViewerCollection

public string GetElementValue(string name)
        {
            if (!HasElement(name))
                return null;
            else
                return _element.Element(name).Value;
        }

19 Source : Program.cs
with MIT License
from CXuesong

static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("ResXToXlf <source.resx> <destination.xlf>");
                Console.WriteLine("This is a tool to copy XML resource file information to the translation standard XLF file https://en.wikipedia.org/wiki/XLIFF.");
                Console.WriteLine("Will copy source resources to destination and show an error if any resource is not in destination.");
                System.Environment.Exit(-1);
            }
            var resx = args[0];
            var xlf = args[1];
            var error = false;
            var reswDoc = XDoreplacedent.Load(resx);
            var sourceEntries = reswDoc.Root.Elements("data").ToDictionary(e => e.Attribute("name").Value,
                                                            e => e.Element("value").Value);
            var xlfDoc = XDoreplacedent.Load(xlf);
            var targetEntries = xlfDoc.Descendants().Where(d => d.Name.LocalName == "trans-unit").
                                 ToDictionary(e => e.Attribute("id").Value,
                                            e => e.Elements().Skip(1).FirstOrDefault());

            foreach (var entry in sourceEntries)
            {
                if (!targetEntries.ContainsKey(entry.Key))
                {
                    error = true;
                    Console.WriteLine("");
                    Console.WriteLine("** Key {0} not found in {1}", entry.Key, xlf);
                    Console.WriteLine("** {0} not modified", xlf);
                    Console.WriteLine("");
                    continue;
                }
                var target = targetEntries[entry.Key];
                target.Value = entry.Value;
                target.Attribute("state").Value = "signed-off";
            }
            if (!error)
            {
                xlfDoc.Save(xlf);
            }
        }

19 Source : NativeBindingsHelper.cs
with MIT License
from Daddoon

private static void _GetReferencedProjects(string projectFile, List<string> projectList)
        {
            try
            {
                projectFile = Path.GetFullPath(projectFile);

                if (projectList.Contains(projectFile))
                    return;

                projectList.Add(projectFile);

                XDoreplacedent projDefinition = XDoreplacedent.Load(projectFile);
                var referencedProjects = projDefinition
                    .Element("Project")
                    .Elements("ItemGroup")
                    .Elements("ProjectReference")
                    .Attributes("Include")
                    .Select(p => Path.GetFullPath(Path.GetDirectoryName(projectFile) + Path.DirectorySeparatorChar + p.Value)) //Force absolute
                    .ToList();

                foreach (string project in referencedProjects)
                {
                    //Recursive search. As each sub-project will not be added twice if absolute path is seen twice it will end automatically
                    _GetReferencedProjects(project, projectList);
                }
            }
            catch (Exception)
            {
                //Ignore if the Project format is incorrect, we must target .NET Core SDK
            }
        }

19 Source : LevelEntities.cs
with GNU General Public License v3.0
from DaneelTrevize

private static XElement getComplex( XElement enreplacedy )
        {
            return enreplacedy.Element( "Complex" );
        }

19 Source : LevelEntities.cs
with GNU General Public License v3.0
from DaneelTrevize

private void trackEnreplacedy( XElement i )
        {
            var id = (UInt64) i.Element( "Simple" ).Attribute( "value" );
            enreplacedyItems.Add( id, i );

            var type = (string) i.Element( "Complex" ).Attribute( "type" );
            if( type == null )
            {
                type = "CUnitGenerator?";      // At least CUnitGenerator enreplacedies lack a type attribute & value, use a placeholder
            }

            SortedSet<UInt64> typeIDs;
            if( !typesToIDs.TryGetValue( type, out typeIDs ) )
            {
                typeIDs = new SortedSet<UInt64>();
                typesToIDs.Add( type, typeIDs );
            }
            typeIDs.Add( id );
        }

19 Source : LevelEntities.cs
with GNU General Public License v3.0
from DaneelTrevize

private void Remove( UInt64 id )
        {
            XElement enreplacedy;
            if( enreplacedyItems.TryGetValue( id, out enreplacedy ) )
            {
                var type = (string) enreplacedy.Element( "Complex" ).Attribute( "type" );
                SortedSet<UInt64> typeIDs;
                if( typesToIDs.TryGetValue( type, out typeIDs ) )
                {
                    typeIDs.Remove( id );
                    // Is OK to leave an empty set of IDs for this type in typesToIDs
                }
                else
                {
                    Console.Error.WriteLine( "Could not remove LevelEnreplacedy by type: " + id );
                }
                enreplacedyItems.Remove( id );

                enreplacedy.Remove();
            }
            else
            {
                Console.Error.WriteLine( "Could not remove LevelEnreplacedy: " + id );
            }
        }

19 Source : LevelEntities.cs
with GNU General Public License v3.0
from DaneelTrevize

internal LinkedList<ScaledEnreplacedy> scaleEnreplacedies( string enreplacedyType, decimal scale, IDGenerator editor )
        {
            if( scale < 0.0M )
            {
                throw new ArgumentOutOfRangeException( "Scale must not be negative." );
            }

            void duplicateLevelEnreplacedy( XElement i, LinkedList<ScaledEnreplacedy> dupedEnreplacedies )
            {
                XElement iCopy = new XElement( i );     // Duplicate at the same position
                var newID = editor.newID();
                iCopy.Element( "Simple" ).SetAttributeValue( "value", newID );
                SaveEditor.getFirstSimplePropertyNamed( iCopy.Element( "Complex" ), "ID" ).SetAttributeValue( "value", newID );

                Add( iCopy );
                dupedEnreplacedies.AddLast( new ScaledEnreplacedy( (UInt64) i.Element( "Simple" ).Attribute( "value" ), newID ) );
            }

            uint multiples = (uint) scale;              // How many duplicates to certainly make of each enreplacedy
            double chance = (double) ( scale % 1 );     // The chance of making 1 more duplicate per enreplacedy

            Random rand = new Random();

            var selectedEnreplacedies = new LinkedList<ScaledEnreplacedy>();

            if( scale < 1.0M )
            {
                // chance is now chance to not remove existing enreplacedies
                // selectedEnreplacedies will be those removed

                // 0 >= scale < 1
                foreach( var i in getEnreplacediesOfTypes( enreplacedyType ) )
                {
                    if( scale == 0.0M || chance < rand.NextDouble() )
                    {
                        var id = (UInt64) i.Element( "Simple" ).Attribute( "value" );
                        Remove( id );
                        selectedEnreplacedies.AddLast( new ScaledEnreplacedy( id ) );
                    }
                }
                //Console.WriteLine( "selectedEnreplacedies: " + selectedEnreplacedies.Count );
            }
            else
            {

                foreach( var i in getEnreplacediesOfTypes( enreplacedyType ) )
                {
                    // First the certain duplications
                    for( uint m = 1; m < multiples; m++ )
                    {
                        duplicateLevelEnreplacedy( i, selectedEnreplacedies );
                    }
                    // And now the chance-based duplication
                    if( chance >= rand.NextDouble() )   // If the chance is not less than the roll
                    {
                        duplicateLevelEnreplacedy( i, selectedEnreplacedies );
                    }
                }
                //Console.WriteLine( "selectedEnreplacedies: " + selectedEnreplacedies.Count );
            }

            return selectedEnreplacedies;
        }

19 Source : LevelEntities.cs
with GNU General Public License v3.0
from DaneelTrevize

internal void swapZombieType( UInt64 id )
        {
            XElement enreplacedy;
            if( enreplacedyItems.TryGetValue( id, out enreplacedy ) )
            {
                /*
                    * change the <Item><Complex type=> from ZX.Enreplacedies.ZombieMutant to ZombieGiant
                    * change the <Item><Complex><Properties><Simple name= value=> IDTemplate, Flags, Size
                    * change the <Item><Complex><Properties><Collection name="Components"><Items><Complex type="ZX.Components.CLife..."><Simple name="Life" value="4000" /> life value
                    * 
                    * mutants have <Item><Complex><Properties><Collection name="Components"><Items><Complex type="ZX.Components.CInflamable..."> but giants don't
                    * 
                    * replace all <Item><Complex><Properties><Collection name="Components"><Items><Complex type="ZX.Components.CBehaviour...>? But keep all
                    * ...<Properties><Complex name="Behaviour"><Properties><Complex name="Data"><Properties><Complex name="InternalData"><Properties><Collection name="OpenNodes"><Items><Simple value=...> values?
                    * A lot of ID numbers are paired with state numbers under ..<Complex name="InternalData"><Properties><Dictionary name="MemCompositorCurrentChild"><Items><Item><Simple value=>
                    * 
                    * The NodeStates Dictionary has Items that aren't unique to each zombie enreplacedy, or uncommon between save files...
                    * 
                    * <Complex type="ZX.Components.CMovable...><Properties><Collection name="Path"><Properties><Simple name="Capacity" value="0" /> is value 4 for Giants
                    * 
                    * (It seems <Simple name="BehaviourModelCheckSum" value=> is always "2014060645", for Mutants or Giants, or Rangers, Ravens, etc)
                    * 
                    * and reset <Item><Complex><Properties><Collection name="Components"><Items><Complex type="ZX.Components.CMovable..."><Properties><Null name="TargetPosition" /> ?
                    * 
                    */

                XElement complex = enreplacedy.Element( "Complex" );
                XElement components = getComponents( enreplacedy );
                XElement cLife = SaveEditor.getComplexItemOfType( components, CLIFE_TYPE );

                XElement path = ( from c in getMovable( enreplacedy ).Element( "Properties" ).Elements( "Collection" )
                                    where (string) c.Attribute( "name" ) == "Path"
                                    select c ).SingleOrDefault();

                string type;
                string flags;
                string template;
                string life;
                string behaviour;
                string pathCapacity;
                string size;
                if( (string) complex.Attribute( "type" ) == MUTANT_TYPE )
                {
                    type = GIANT_TYPE;
                    flags = "None";
                    template = GIANT_ID_TEMPLATE;
                    life = GIANT_LIFE;
                    behaviour = GIANT_BEHAVIOUR_TYPE;
                    pathCapacity = "4";
                    size = GIANT_SIZE;

                    XElement cInflamable = SaveEditor.getComplexItemOfType( components, CINFLAMABLE, false );
                    if( cInflamable != null )
                    {
                        cInflamable.Remove();
                    }
                }
                else
                {
                    type = MUTANT_TYPE;
                    flags = "IsOneCellSize";
                    template = MUTANT_ID_TEMPLATE;
                    life = MUTANT_LIFE;
                    behaviour = MUTANT_BEHAVIOUR_TYPE;
                    pathCapacity = "0";
                    size = MUTANT_SIZE;

                    string cInflamable =
                    @"<Complex type=""ZX.Components.CInflamable, TheyAreBillions"">
                    <Properties>
                        <Complex name=""EnreplacedyRef"">
                        <Properties>
                            <Simple name=""IDEnreplacedy"" value=""0"" />
                        </Properties>
                        </Complex>
                        <Null name=""Fire"" />
                        <Simple name=""TimeUnderFire"" value=""0"" />
                    </Properties>
                    </Complex>";
                    XElement inflamable = XElement.Parse( cInflamable );
                    components.Element( "Items" ).Add( inflamable );
                }

                complex.Attribute( "type" ).SetValue( type );
                SaveEditor.getFirstSimplePropertyNamed( complex, "Flags" ).Attribute( "value" ).SetValue( flags );
                SaveEditor.getFirstSimplePropertyNamed( complex, "IDTemplate" ).Attribute( "value" ).SetValue( template );
                SaveEditor.getFirstSimplePropertyNamed( cLife, "Life" ).Attribute( "value" ).SetValue( life );
                getBehaviour( enreplacedy ).Attribute( "type" ).SetValue( behaviour );
                SaveEditor.getFirstSimplePropertyNamed( path, "Capacity" ).Attribute( "value" ).SetValue( pathCapacity );
                SaveEditor.getFirstSimplePropertyNamed( complex, "Size" ).Attribute( "value" ).SetValue( size );
            }
            else
            {
                Console.Error.WriteLine( "Could not type-swap LevelEnreplacedy: " + id );
            }
        }

19 Source : LevelEntities.cs
with GNU General Public License v3.0
from DaneelTrevize

internal void resizeVODs( SaveEditor.VodSizes vodSize )
        {
            string newType;
            string newIDTemplate;
            string newLife;
            string newSize;
            switch( vodSize )
            {
                default:
                case SaveEditor.VodSizes.SMALL:
                    newType = VOD_SMALL_TYPE;
                    newIDTemplate = VOD_SMALL_ID_TEMPLATE;
                    newLife = VOD_SMALL_LIFE;
                    newSize = VOD_SMALL_SIZE;
                    break;
                case SaveEditor.VodSizes.MEDIUM:
                    newType = VOD_MEDIUM_TYPE;
                    newIDTemplate = VOD_MEDIUM_ID_TEMPLATE;
                    newLife = VOD_MEDIUM_LIFE;
                    newSize = VOD_MEDIUM_SIZE;
                    break;
                case SaveEditor.VodSizes.LARGE:
                    newType = VOD_LARGE_TYPE;
                    newIDTemplate = VOD_LARGE_ID_TEMPLATE;
                    newLife = VOD_LARGE_LIFE;
                    newSize = VOD_LARGE_SIZE;
                    break;
            }
            /*
             * To change VOD building sizes:
             * Change the <Complex type=
             * Change the   <Properties>
                              <Simple name="IDTemplate" value=
             * Change the     <Collection name="Components" elementType="DXVision.DXComponent, DXVision">
                                <Items>
                                  <Complex type="ZX.Components.CLife, TheyAreBillions">
                                    <Properties>
                                      <Simple name="Life" value=
             * Change the
                  <Simple name="Size" value=
             *
             * Ignore?        <Complex type="ZX.Components.CTransparentIfNearUnits, TheyAreBillions">
                                <Properties>
                                  <Simple name="HiddingUnits" value="False" />
                                  <Simple name="CheckHiddingUnits" value="False" />
             */

            IEnumerable<XElement> vodItems = getEnreplacediesOfTypes( VOD_SMALL_TYPE, VOD_MEDIUM_TYPE, VOD_LARGE_TYPE );
            //Console.WriteLine( "vodItems: " + vodItems.Count() );

            foreach( XElement v in vodItems.ToList() )  // no ToList() leads to only removing 1 <item> per save modify cycle?!
            {
                XElement complex = v.Element( "Complex" );
                complex.SetAttributeValue( "type", newType );
                SaveEditor.getFirstSimplePropertyNamed( complex, "IDTemplate" ).SetAttributeValue( "value", newIDTemplate );
                SaveEditor.getFirstSimplePropertyNamed( SaveEditor.getComplexItemOfType( SaveEditor.getComponents( complex ), CLIFE_TYPE ), "Life" ).SetAttributeValue( "value", newLife );
                SaveEditor.getFirstSimplePropertyNamed( complex, "Size" ).SetAttributeValue( "value", newSize );
            }
        }

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

void AddAndroidPermissions(IEnumerable<string> permissions)
        {
            var newElements = permissions.Select(p => new XElement("uses-permission", new XAttribute(aName, p)));

            var lastPerm = manifest.Elements("uses-permission").LastOrDefault();
            if (lastPerm != null)
            {
                foreach (var el in newElements)
                {
                    lastPerm.AddAfterSelf(el);
                    lastPerm = el;
                }
            }
            else
            {
                var parentNode = (XNode)manifest.Element("application") ?? manifest.LastNode;
                foreach (var el in newElements)
                    parentNode.AddBeforeSelf(el);
            }
        }

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

IEnumerable<XElement> GetLaunchableActivities()
        {
            foreach (var activity in application.Elements("activity"))
            {
                var filter = activity.Element("intent-filter");
                if (filter != null)
                {
                    foreach (var category in filter.Elements("category"))
                        if (category != null && (string)category.Attribute(aName) == "android.intent.category.LAUNCHER")
                            yield return activity;
                }
            }
        }

19 Source : AzureDevOpsClient.cs
with MIT License
from Deliveron

private static Report GetReport(string filePath, string url)
        {
            XmlDoreplacedent doc = new XmlDoreplacedent();
            doc.Load(filePath);

            string response = doc.InnerXml;

            if (response != null)
            {
                XDoreplacedent doreplacedent = XDoreplacedent.Parse(response);

                IEnumerable<XElement> elements =
                    doreplacedent.Element("OWASPZAPReport")
                        .Elements("site")
                        .Where(e => e.Attribute("host").Value == new Uri(url).Host);

                var issues = new List<Issue>();
                foreach (XElement element in elements)
                {
                    issues.AddRange(
                        from e in element.Descendants("alerreplacedem")
                        select new Issue
                        {
                            IssueDescription = e.Element("alert").Value,
                            RiskDescription = e.Element("riskdesc").Value,
                            OriginalSiteUrl = element.Attribute("name").Value,
                            Description = e.Element("desc").Value,
                            Solution = e.Element("solution").Value,
                            Instances = (from i in e.Descendants("instance")
                                         select new IssueInstance
                                         {
                                             Uri = i.Element("uri").Value,
                                             Evidence = i.Element("evidence") != null ? i.Element("evidence").Value : ""
                                            }).ToList()

                        }) ;; ;
                           
                }
                return new Report { Issues = issues };
            }
            return null;
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessDataSetCore(XElement dataSetElement, DataSetConversionState conversionState, string componentName) {
            var ns = dataSetElement.GetDefaultNamespace();
            var dataSetInfo = dataSetElement.Element(rdns + "DataSetInfo");
            var sharedDataSet = dataSetElement.Element(ns + "SharedDataSet");
            if(sharedDataSet != null) {
                ProcessSharedDataSet(sharedDataSet, conversionState, componentName);
            } else {
                var dataSourceName = dataSetElement.Descendants(ns + "DataSourceName").SingleOrDefault()?.Value;
                if(dataSourceName == null) {
                    var dataSourceReference = dataSetElement.Descendants(ns + "DataSourceReference").SingleOrDefault();
                    if(dataSourceReference != null) {
                        if(!dataSourceReferenceToDataSourceNameMap.TryGetValue(dataSourceReference.Value, out dataSourceName))
                        dataSourceReferenceToDataSourceNameMap[dataSourceReference.Value] = dataSourceName = dataSourceReference.Value;
                    }
                }
                conversionState.DataSource = GetOrAddDataSource(dataSourceName);
                if(dataSetInfo != null) {
                    var externalConverter = new ExternalDataSetConverter(this, typeResolver, designerHost, currentProjectRootNamespace);
                    if(externalConverter.Convert(dataSetInfo, conversionState))
                        return;
                }
            }
            if(conversionState.DataSource == null)
                return;
            var fieldsElement = dataSetElement.Element(ns + "Fields");
            if(fieldsElement != null)
                ProcessDataSetFields(fieldsElement, conversionState);

            var queryElement = dataSetElement.Element(ns + "Query");
            if(queryElement != null && !conversionState.DataSource.Queries.Any(x => x.Name == conversionState.DataSetName))
                ProcessQuery(queryElement, conversionState, componentName);
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessSharedDataSet(XElement sharedDataSet, DataSetConversionState state, string componentName) {
            var dataSetName = sharedDataSet.Element(sharedDataSet.GetDefaultNamespace() + "SharedDataSetReference").Value;
            var doreplacedent = GetSharedResourceDoreplacedent(converter.ReportFolder, dataSetName, "rsd");
            if(doreplacedent == null) {
                Tracer.TraceWarning(NativeSR.TraceSource, string.Format(Messages.DataSource_MissingSharedDataSet_Format, dataSetName));
                return;
            }
            var ns = doreplacedent.Root.GetDefaultNamespace();
            var dataSourceReference = doreplacedent.Root.Descendants(ns + "DataSourceReference").Single();
            var referenceName = dataSourceReference.Value;
            string dataSourceName;
            if(dataSourceReferenceToDataSourceNameMap.TryGetValue(referenceName, out dataSourceName)) {
                state.DataSource = GetOrAddDataSource(dataSourceName);
            } else {
                state.DataSource = GetOrAddDataSource(referenceName);
                dataSourceReferenceToDataSourceNameMap[referenceName] = state.DataSource.Name;
                ProcessDataSourceReference(dataSourceReference, state.DataSource);
            }
            var dataSet = doreplacedent.Root.Element(ns + "DataSet");
            ProcessDataSetCore(dataSet, state, componentName);
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessDataSetFields(XElement fields, DataSetConversionState state) {
            var ns = fields.GetDefaultNamespace();
            if(FieldListResultSchemaProvider.ResultSetContains(state.DataSource, state.DataSetName))
                return;
            var columns = fields.Elements(ns + "Field")
                .Select(field => {
                    var name = field.Attribute("Name").Value;
                    var typeName = field.Element(rdns + "TypeName")?.Value;
                    var type = string.IsNullOrEmpty(typeName) ? typeof(object) : Type.GetType(typeName);
                    if(type == null) {
                        Tracer.TraceInformation(NativeSR.TraceSource, string.Format(Messages.DataSource_CannotResolveColumnType_Format, typeName));
                        type = typeof(object);
                    }
                    return new { Name = name, Type = type };
                }).ToDictionary(x => x.Name, x => x.Type);
            FieldListResultSchemaProvider.AppendViewToSchema(state.DataSource, state.DataSetName, columns);
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessQuery(XElement queryElement, DataSetConversionState state, string componentName) {
            var ns = queryElement.GetDefaultNamespace();
            var commandType = queryElement.Element(ns + "CommandType")?.Value ?? "Text";
            var commandText = queryElement.Element(ns + "CommandText").Value;
            if(commandText == "/* Local Query */")
                return;
            state.Query = GetOrAddQuery(state, commandType, commandText);
            if(state.Query == null)
                return;
            ProcessDataSetParameters(queryElement.Element(ns + "DataSetParameters"), state);
            ProcessQueryParameters(queryElement.Element(ns + "QueryParameters"), state, componentName);
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessQueryParameters(XElement queryParameters, DataSetConversionState state, string componentName) {
            if(queryParameters == null)
                return;
            var ns = queryParameters.GetDefaultNamespace();
            IEnumerable<XElement> queryParameterElements = queryParameters.Elements(ns + "QueryParameter");
            foreach(var queryParameterElement in queryParameterElements) {
                QueryParameter queryParameter = GetOrAddQueryParameter(queryParameterElement, state);
                var value = queryParameterElement.Element(ns + "Value").Value;

                ExpressionParserResult expressionResult;
                if(converter.TryGetExpression(value, $"{componentName}.{queryParameter.Name}", out expressionResult)) {
                    queryParameter.Value = expressionResult.ToDataAccessExpression(typeof(string));
                    queryParameter.Type = typeof(DataAccess.Expression);
                } else {
                    queryParameter.Value = value;
                    queryParameter.Type = typeof(string);
                }
            }
        }

19 Source : ExternalDataSetConverter.cs
with MIT License
from DevExpress

public bool Convert(XElement dataSetInfo, DataSetConversionState state) {
            var dataSetName = dataSetInfo.Element(rdns + "DataSetName")?.Value;
            if(string.IsNullOrEmpty(dataSetName))
                return false;
            var dataSetSchemaPath = dataSetInfo.Element(rdns + "SchemaPath")?.Value ?? dataSetName;
            var tableName = dataSetInfo.Element(rdns + "TableName").Value;
            var dataSetType = ResolveDataSetType(dataSetName);
            DataSet dataSet = null;
            if(dataSetType != null) {
                try {
                    dataSet = Activator.CreateInstance(dataSetType) as DataSet;
                } catch { }
            }

            if(!TryConvertWithConverter(dataSet, state)) {
                var schemaDoreplacedent = dataSourceConverter.GetSharedResourceDoreplacedent(dataSetSchemaPath, "xsd");
                if(schemaDoreplacedent != null) {
                    Tracer.TraceInformation(NativeSR.TraceSource, new FormattableString(Messages.DataSource_CannotResolveDataSet_Format, dataSetName));
                    ProcessSchema(schemaDoreplacedent, state);
                } else {
                    Tracer.TraceInformation(NativeSR.TraceSource, new FormattableString(Messages.DataSource_CannotProcessDataSet_Format, dataSetName));
                    return false;
                }
            }
            state.Query = state.DataSource.Queries.SingleOrDefault(x => x.Name == tableName);
            return state.Query != null;
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessDataSource(XElement dataSourceElement) {
            var ns = dataSourceElement.GetDefaultNamespace();
            var dataSourceName = dataSourceElement.Attribute("Name").Value;
            var dataSourceReference = dataSourceElement.Element(ns + "DataSourceReference");
            if(dataSourceReference != null) {
                string storedDataSourceName;
                if(dataSourceReferenceToDataSourceNameMap.TryGetValue(dataSourceReference.Value, out storedDataSourceName))
                    return;
                else dataSourceReferenceToDataSourceNameMap[dataSourceReference.Value] = dataSourceName;
            }
            var sqlDataSource = GetOrAddDataSource(dataSourceElement.Attribute("Name")?.Value);
            ReportingServicesConverter.IterateElements(dataSourceElement, (e, name) => {
                switch(name) {
                    case "DataSourceReference":
                        ProcessDataSourceReference(e, sqlDataSource);
                        break;
                    case "ConnectionProperties":
                        if(dataSourceReference == null)
                            ProcessConnectionProperties(e, sqlDataSource);
                        break;
                    case "SecurityType":         //handled
                    case "IntegratedSecurity":   //handled
                    case "DataSourceID":
                    case "Transaction":
                        break;
                    default:
                        Tracer.TraceInformation(NativeSR.TraceSource, string.Format(Messages.DataSource_Element_NotSupported_Format, name));
                        break;
                }
            });
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessDataSourceReference(XElement reference, SqlDataSource dataSource) {
            XDoreplacedent doreplacedent = GetSharedResourceDoreplacedent(converter.ReportFolder, reference.Value, "rds");
            if(doreplacedent != null) {
                var ns = doreplacedent.Root.GetDefaultNamespace();
                ProcessConnectionProperties(doreplacedent.Root.Element(ns + "ConnectionProperties"), dataSource);
            }
        }

19 Source : DataSourceConverter.cs
with MIT License
from DevExpress

void ProcessConnectionProperties(XElement connection, SqlDataSource dataSource) {
            var ns = connection.GetDefaultNamespace();
            var dataProvider = connection.Element(ns + "DataProvider")?.Value ?? connection.Element(ns + "Extension")?.Value;
            var connectionString = connection.Element(ns + "ConnectString").Value;
            var integratedSecurity = connection.Element(ns + "IntegratedSecurity")?.Value == "true";
            if(ReportingServicesConverter.IsExpression(connectionString))
                Tracer.TraceInformation(NativeSR.TraceSource, Messages.DataSource_ConnectionParameters_Expression_NotSupported);
            else
                dataSource.ConnectionParameters = CreateConnectionParameters(dataProvider, connectionString, integratedSecurity, is2016OrHigher: IsVersionHigherThan2016(ns.NamespaceName));
        }

19 Source : HeaderModel.cs
with MIT License
from DevExpress

public static HeaderModel Parse(XElement element, UnitConverter unitConverter) {
            if(element == null)
                return null;
            XNamespace ns = element.GetDefaultNamespace();
            float size = unitConverter.ToFloat(element.Element(ns + "Size").Value);
            XElement cell = element.Element(ns + "CellContents");
            return new HeaderModel(size, cell);
        }

19 Source : Model.cs
with MIT License
from DevExpress

public static Model Parse(XElement element, UnitConverter unitConverter, IReportingServicesConverter converter) {
            XNamespace ns = element.GetDefaultNamespace();
            string name = element.Attribute("Name").Value;
            var bounds = new RectangleF(
                unitConverter.ToFloat(element.Element(ns + "Left")?.Value),
                unitConverter.ToFloat(element.Element(ns + "Top")?.Value),
                unitConverter.ToFloat(element.Element(ns + "Width")?.Value),
                unitConverter.ToFloat(element.Element(ns + "Height")?.Value));
            XElement body = element.Element(ns + "TablixBody");
            List<float> columns = body
                .Element(ns + "TablixColumns")
                .Elements(ns + "TablixColumn")
                .Select(x => unitConverter.ToFloat(x.Element(ns + "Width").Value))
                .ToList();
            List<RowModel> rows = body
                .Element(ns + "TablixRows")
                .Elements(ns + "TablixRow")
                .Select(x => RowModel.Parse(x, unitConverter))
                .ToList();
            Hierarchy rowHierarchy = Hierarchy.Parse(element.Element(ns + "TablixRowHierarchy"), name, converter);
            Hierarchy columnHierarchy = Hierarchy.Parse(element.Element(ns + "TablixColumnHierarchy"), name, converter);
            string dataSetName = element.Element(ns + "DataSetName")?.Value;
            CriteriaOperator filter = Filter.ParseFilters(element.Element(ns + "Filters"), name, converter);
            List<SortExpressionMember> sortExpressions = SortExpressionMember.Parse(element.Element(ns + "SortExpressions"), name, converter);
            return new Model(name, bounds, element, columns, rows, rowHierarchy, columnHierarchy, dataSetName, filter, sortExpressions);
        }

19 Source : SortExpressionMember.cs
with MIT License
from DevExpress

static SortExpressionMember ParseSingle(XElement sortExpressionElement, string componentName, IReportingServicesConverter converter) {
            XNamespace ns = sortExpressionElement.GetDefaultNamespace();
            CriteriaOperator criteria = converter.ParseExpression(sortExpressionElement.Element(ns + "Value").Value, componentName);
            string directionString = sortExpressionElement.Element(ns + "Direction")?.Value;
            XRColumnSortOrder direction = directionString == "Descending" ? XRColumnSortOrder.Descending : XRColumnSortOrder.Ascending;
            return new SortExpressionMember(criteria, direction);
        }

19 Source : TablixMember.cs
with MIT License
from DevExpress

public static List<TablixMember> ParseContainer(XElement containerElement, string componentName, IReportingServicesConverter converter) {
            XNamespace ns = containerElement.GetDefaultNamespace();
            XElement tablixMembersElement = containerElement.Element(ns + "TablixMembers");
            if(tablixMembersElement == null)
                return new List<TablixMember>();
            List<TablixMember> tablixMembers = tablixMembersElement
                .Elements(ns + "TablixMember")
                .Select(x => Parse(x, componentName, converter))
                .ToList();
            return tablixMembers;
        }

See More Examples