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

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

780 Examples 7

19 Source : PackageIndex.cs
with MIT License
from dotnet

public void MergeFrameworkList(NuGetFramework framework, string frameworkListPath, bool addPackages = true)
        {
            XDoreplacedent frameworkList = XDoreplacedent.Load(frameworkListPath);
            foreach (var file in frameworkList.Element("FileList").Elements("File"))
            {
                string replacedemblyName = file.Attribute("replacedemblyName").Value;
                var versionAttribute = file.Attribute("Version");
                Version supportedVersion = (versionAttribute != null) ? new Version(versionAttribute.Value) : VersionUtility.MaxVersion;

                TryAddInbox(replacedemblyName, framework, supportedVersion, addPackages);
            }
        }

19 Source : Program.cs
with MIT License
from dotnet

private static Dictionary<string, string> ParsePackageVersions(XDoreplacedent packagesDoreplacedent, string repoName)
        {
            var props = new Dictionary<string, string>();
            IEnumerable<XElement> propGroups = packagesDoreplacedent?.Element("Project")?.Elements("PropertyGroup");
            if (propGroups != null)
            {
                foreach (XElement propGroup in propGroups)
                {
                    if (propGroup.Attribute("Condition") != null)
                    {
                        WriteWarning($"{repoName} Packages.prop has Conditional PropertyGroup, which is not supported");
                        continue;
                    }

                    foreach (XElement prop in propGroup.Elements())
                    {
                        if (prop.Attribute("Condition") != null)
                        {
                            WriteWarning(
                                $"{repoName} Packages.prop property {prop.Name.LocalName} has Conditional Property, which is not supported");
                            continue;
                        }

                        props[prop.Name.LocalName] = prop.Value;
                    }
                }
            }

            var versions = new Dictionary<string, string>();
            IEnumerable<XElement> packageReferences = packagesDoreplacedent?.Element("Project")
                ?.Elements("ItemGroup")
                ?.Elements("PackageReference");
            if (packageReferences == null)
            {
                WriteError($"No PackageReferences found in {repoName} Packages.props");
            }
            else
            {
                foreach (XElement packageRef in packageReferences)
                {
                    string name = packageRef.Attribute("Update")?.Value;
                    string version = packageRef.Attribute("Version")?.Value;

                    if (string.IsNullOrEmpty(name))
                    {
                        WriteWarning($"PackageReference with no 'Update' found in Packages.props for repo {repoName}");
                        continue;
                    }

                    if (string.IsNullOrEmpty(version))
                    {
                        WriteWarning(
                            $"PackageReference with no 'Version' for Package '{name}' found in Packages.props for repo {repoName}");
                        continue;
                    }

                    version = Regex.Replace(version,
                        @"\$\(([A-Za-z0-9_]*)\)",
                        m => props.GetValueOrDefault(m.Groups[1].Value, m.Groups[0].Value));

                    versions.Add(name, version);
                }
            }

            return versions;
        }

19 Source : TestAssetInstance.cs
with MIT License
from dotnet

private void CopyNugetConfigAdjustingPath(FileInfo source, FileInfo destination)
        {
            var doc = XDoreplacedent.Load(source.FullName, LoadOptions.PreserveWhitespace);
            foreach (var packageSource in doc.Root.Element("packageSources").Elements("add").Attributes("value"))
            {
                if (!Path.IsPathRooted(packageSource.Value))
                {
                    string fullPathAtSource = Path.GetFullPath(Path.Combine(source.Directory.FullName, packageSource.Value));
                    if (!PathUtility.IsChildOfDirectory(TestreplacedetInfo.Root.FullName, fullPathAtSource))
                    {
                        packageSource.Value = fullPathAtSource;
                    }
                }

                using (var file = new FileStream(
                    destination.FullName,
                    FileMode.CreateNew,
                    FileAccess.ReadWrite))
                {
                    doc.Save(file, SaveOptions.None);
                }
            }
        }

19 Source : NuGetV2ServiceFeed.cs
with MIT License
from dotnet

private static IReadOnlyList<string> GetPackageVersionsFromNuGetV2CompatibleQueryResult(string id, XDoreplacedent doreplacedent)
        {
            List<string> results = new List<string>();

            if (doreplacedent != null)
            {
                foreach (var el in doreplacedent.Root.Elements(doreplacedent.Root.GetDefaultNamespace() + "entry"))
                {
                    var pkgId = GetPropertyValue(doreplacedent, el, "Id");

                    var pkgVersion = GetPropertyValue(doreplacedent, el, "Version");

                    if (pkgId.Equals(pkgId, StringComparison.OrdinalIgnoreCase))
                    {
                        results.Add(pkgVersion);
                    }
                }
            }

            return results;
        }

19 Source : NuGetV2ServiceFeed.cs
with MIT License
from dotnet

private static IReadOnlyList<string> GetPackageNamesFromNuGetV2CompatibleQueryResult(XDoreplacedent doreplacedent)
        {
            List<string> results = new List<string>();

            if (doreplacedent != null)
            {
                foreach (var el in doreplacedent.Root.Elements(doreplacedent.Root.GetDefaultNamespace() + "entry"))
                {
                    var id = GetPropertyValue(doreplacedent, el, "Id");

                    results.Add(id);
                }
            }

            return results.Distinct().ToList();
        }

19 Source : CommandDefinition.cs
with MIT License
from dotnet

public static CommandDefinition CreateFromXml(XElement xe)
        {
            Require.Equal("command", xe.Name);

            if (!(xe.Attribute("alias") is null))
            {
                var ret = CreateFromXml
                (
                    xe.Doreplacedent?.Element("registry")
                        ?.Elements("commands")
                        .Elements("command")
                        .FirstOrDefault(x => x.Element("proto")?.Element("name")?.Value == xe.Attribute("alias")?.Value)
                );

                return new CommandDefinition
                    (xe.GetNameAttribute(), ret.ReturnType, ret.Parameters, ret.SuccessCodes, ret.ErrorCodes);
            }

            var proto = xe.Element("proto");
            var name = proto?.Element("name")?.Value;
            var returnTypeName = proto?.Element("type")?.Value;
            var returnType = new TypeSpec(returnTypeName);

            // ReSharper disable StringLiteralTypo
            var successAttr = xe.Attribute("successcodes");
            var successCodes = successAttr != null
                ? successAttr.Value.Split(',').ToArray()
                : Array.Empty<string>();
            
            var errorAttr = xe.Attribute("errorcodes");
            var errorCodes = errorAttr != null
                ? errorAttr.Value.Split(',').ToArray()
                : Array.Empty<string>();
            
            // ReSharper restore StringLiteralTypo

            var parameters = xe.Elements("param")
                .Select(ParameterDefinition.CreateFromXml)
                .ToArray();

            return new CommandDefinition(name, returnType, Vary(parameters, name), successCodes, errorCodes);
        }

19 Source : ConstantDefinition.cs
with MIT License
from dotnet

public static ConstantDefinition CreateFromXml(XElement xe)
        {
            Require.NotNull(xe);

            if (!(xe.Attribute("alias") is null))
            {
                var ret = CreateFromXml
                (
                    xe.Doreplacedent?.Element("registry")?
                        .Elements("enums")
                        .Where(x => x.Attribute("name")?.Value == "API Constants")
                        .SelectMany(x => x.Elements("enum"))
                        .FirstOrDefault(x => x.Attribute("name")?.Value == xe.Attribute("alias")?.Value)
                );

                return new ConstantDefinition(xe.Attribute("name")?.Value, ret.Value, ret.Comment);
            }

            var name = xe.GetNameAttribute();
            var value = xe.Attribute("value")?.Value;
            var comment = xe.Attribute("comment")?.Value;

            return new ConstantDefinition(name, value, comment);
        }

19 Source : EnumDefinition.cs
with MIT License
from dotnet

public static EnumDefinition CreateFromXml(XElement xe)
        {
            Require.NotNull(xe);

            EnumType type;
            var typeAttr = xe.Attribute("type");
            if (typeAttr != null)
            {
                var typeString = xe.Attribute("type")?.Value ?? throw new InvalidDataException();
                type = (EnumType)Enum.Parse(typeof(EnumType), typeString, true);
            }
            else
            {
                type = EnumType.Constants;
            }

            var name = xe.Attribute("name")?.Value;
            var values = xe.Elements("enum").Select(EnumValue.CreateFromXml).ToArray();
            var bitWidth = xe.Attribute("bitwidth")?.Value;
            return new(name, type, values, bitWidth is null ? 32 : int.Parse(bitWidth));
        }

19 Source : EnumDefinition.cs
with MIT License
from dotnet

public static EnumValue CreateFromXml(XElement xe)
        {
            Require.NotNull(xe);

            if (!(xe.Attribute("alias") is null))
            {
                var ret = CreateFromXml
                (xe.Doreplacedent?.Element("registry")
                    ?.Elements("enums")
                    .Where
                    (
                        x => x.GetTypeAttributeOrNull() == "enum" ||
                                 x.GetTypeAttributeOrNull() == "bitmask"
                    )
                    .Elements("enum")
                    .FirstOrDefault(x => x.Attribute("name")?.Value == xe.Attribute("alias")?.Value));
                
                return new EnumValue(xe.Attribute("name")?.Value, ret.Value, ret.Comment);
            }

            var name = xe.Attribute("name")?.Value;

            long value;
            var valueStr = xe.Attribute("value")?.Value;
            if (valueStr != null)
            {
                if (valueStr.StartsWith("0x"))
                {
                    valueStr = valueStr.Substring(2);
                    value = long.Parse(valueStr, NumberStyles.HexNumber);
                }
                else
                {
                    value = long.Parse(valueStr);
                }
            }
            else
            {
                var bitposStr = xe.Attribute("bitpos")?.Value;
                value = 1L << int.Parse(bitposStr ?? throw new InvalidDataException());
            }

            var commentAttr = xe.Attribute("comment");
            var comment = commentAttr != null ? commentAttr.Value : string.Empty;
            return new EnumValue(name, value, comment);
        }

19 Source : ExtensionDefinition.cs
with MIT License
from dotnet

public static ExtensionDefinition CreateFromXml(XElement xe)
        {
            var name = xe.GetNameAttribute();
            var numberString = xe.Attribute("number")?.Value ?? throw new InvalidDataException();
            var number = int.Parse(numberString);
            var type = xe.GetTypeAttributeOrNull();
            var extensionConstants = new List<ExtensionConstant>();
            var enumExtensions = new List<EnumExtensionValue>();
            var commandNames = new List<string>();
            var typeNames = new List<string>();
            var supported = xe.Attribute("supported")?.Value.Split('|');

            foreach (var require in xe.Elements("require"))
            {
                foreach (var enumXe in require.Elements("enum"))
                {
                    ParseEnumRequirement(enumXe, number, enumExtensions, name, extensionConstants);
                }

                commandNames.AddRange(require.Elements("command").Select
                (
                    commandXe => commandXe.GetNameAttribute())
                );

                typeNames.AddRange(require.Elements("type").Select
                (
                    typeXe => typeXe.GetNameAttribute())
                );
            }
            
            return new ExtensionDefinition
            (
                name,
                number,
                type,
                extensionConstants.ToArray(),
                enumExtensions.ToArray(),
                commandNames.ToArray(),
                typeNames.ToArray(),
                supported
            );
        }

19 Source : FeatureDefinition.cs
with MIT License
from dotnet

private static string ParseEnumRequirement(XElement enumXe, int originalNumber, ICollection<EnumExtensionValue> enumExtensions)
        {
            var enumName = enumXe.GetNameAttribute();
            
            Debug.replacedert(enumXe.Doreplacedent != null);

            var number = enumXe.Attribute("extnumber") is null
                ? originalNumber
                : int.Parse(enumXe.Attribute("extnumber")?.Value ?? throw new InvalidDataException());

            if (!(enumXe.Attribute("alias") is null))
            {
                var dummyValues = new List<EnumExtensionValue>();
                ParseEnumRequirement
                (
                    enumXe.Doreplacedent.Element("registry")
                        ?.Elements("extensions")
                        .Elements("extension")
                        .Concat(enumXe.Doreplacedent.Element("registry")?.Elements("feature")
                                ?? throw new InvalidDataException())
                        .Elements("require")
                        .Elements("enum")
                        .Concat(enumXe.Doreplacedent.Element("registry")?.Elements("enums").Elements("enum")
                                ?? throw new InvalidDataException())
                        .FirstOrDefault(x => x.GetNameAttribute() == enumXe.Attribute("alias")?.Value), number,
                    dummyValues
                );
                foreach (var dummyValue in dummyValues)
                {
                    enumExtensions.Add(new EnumExtensionValue(dummyValue.ExtendedType, enumName, dummyValue.Value));
                }
                
                return enumName;
            }

            var extends = enumXe.Attribute("extends")?.Value;
            if (extends != null)
            {
                string valueString;
                var offsetString = enumXe.Attribute("offset")?.Value;
                if (offsetString != null)
                {
                    var offset = int.Parse(offsetString);
                    var direction = 1;
                    if (enumXe.Attribute("dir")?.Value == "-")
                    {
                        direction = -1;
                    }

                    var value = direction * (1000000000 + (number - 1) * 1000 + offset);
                    valueString = value.ToString();
                }
                else
                {
                    var bitPosString = enumXe.Attribute("bitpos")?.Value;
                    if (bitPosString != null)
                    {
                        var shift = int.Parse(bitPosString);
                        valueString = (1L << shift).ToString();
                    }
                    else
                    {
                        valueString = enumXe.Attribute("value")?.Value;
                    }
                }
                enumExtensions.Add(new EnumExtensionValue(extends, enumName, valueString));
            }

            return enumName;
        }

19 Source : OpenCLReader.cs
with MIT License
from dotnet

public IEnumerable<Function> ReadFunctions(object obj, BindTask task)
        {
            var doc = obj as XDoreplacedent;
            Debug.replacedert(doc != null, nameof(doc) + " != null");
            
            var registry = doc.Element("registry");
            Debug.replacedert(registry != null, $"{nameof(registry)} != null");
            
            var allFunctions = registry
                .Elements("commands")
                .Elements("command")
                .Select(x => TranslateCommand(x, task))
                .ToDictionary(x => x.Attribute("name")?.Value, x => x);
            Debug.replacedert(allFunctions != null, nameof(allFunctions) + " != null");
            
            var apis = registry.Elements("feature")
                .Concat(registry
                    .Elements("extensions")
                    .Elements("extension") ?? throw new InvalidDataException());
            
            Debug.replacedert(apis != null, nameof(apis) + " != null");
            
            var removals = registry.Elements("feature")
                .Elements("remove")
                .Elements("command")
                .Attributes("name")
                .Select(x => x.Value)
                .ToList();
            
            Debug.replacedert(removals != null, nameof(removals) + " != null");
            
            foreach (var api in apis)
            {
                foreach (var requirement in api.Elements("require"))
                {
                    var apiName = requirement.Attribute("api")?.Value ??
                                  api.Attribute("api")?.Value ??
                                  api.Attribute("supported")?.Value ??
                                  "opencl";
                    var apiVersion = api.Attribute("number") != null
                        ? Version.Parse(api.Attribute("number")?.Value ?? throw new InvalidDataException())
                        : null;
                    foreach (var name in apiName.Split('|'))
                    {
                        foreach (var function in requirement.Elements("command")
                            .Attributes("name")
                            .Select(x => x.Value))
                        {
                            var xf = allFunctions[TrimName(function, task)];
                            
                            var ret = new Function
                            {
                                Attributes = removals.Contains(function)
                                    ? new List<Attribute>
                                    {
                                        new Attribute
                                        {
                                            Name = "System.Obsolete",
                                            Arguments = new List<string>
                                            {
                                                $"\"Deprecated in version {apiVersion?.ToString(2)}\""
                                            }
                                        }
                                    }
                                    : new List<Attribute>(),
                                Categories = new List<string>{ExtensionName(api.Attribute("name")?.Value, task)},
                                Doc = string.Empty,
                                ExtensionName = api.Name == "feature" ? "Core" : ExtensionName(api.Attribute("name")?.Value, task),
                                GenericTypeParameters = new List<GenericTypeParameter>(),
                                Name = Naming.Translate(NameTrimmer.Trim(TrimName(xf.Attribute("name")?.Value, task), task.FunctionPrefix), task.FunctionPrefix),
                                NativeName = function,
                                Parameters = ParseParameters(xf),
                                ProfileName = name,
                                ProfileVersion = apiVersion,
                                ReturnType = ParseTypeSignature(xf.Element("returns") ?? throw new InvalidDataException())
                            };

                            yield return ret;

                            allFunctions.Remove(function);
                        }
                    }
                }
            }
        }

19 Source : OpenCLReader.cs
with MIT License
from dotnet

private XElement TranslateCommand(XContainer command, BindTask task)
        {
            var function = new XElement("function");

            var cmdName = FunctionName(command, task);
            var name = new XAttribute("name", cmdName);

            var returns = new XElement
            (
                "returns",
                command.Element("proto")?.Attribute("group") is null ? new object[]{new XAttribute
                (
                    "type",
                    FunctionParameterType(command.Element("proto"))
                        .Replace("const", string.Empty)
                        .Replace("struct", string.Empty)
                        .Replace("String *", "String")
                        .Trim()
                )} : new object[]{new XAttribute
                (
                    "type",
                    FunctionParameterType(command.Element("proto"))
                        .Replace("const", string.Empty)
                        .Replace("struct", string.Empty)
                        .Replace("String *", "String")
                        .Trim()
                ), new XAttribute("group", command.Element("proto")?.Attribute("group")?.Value ?? throw new InvalidDataException())}
            );

            foreach (var parameter in command.Elements("param"))
            {
                var param = FunctionParameterType(parameter);

                var p = new XElement("param");
                string randomName = null;
                if (parameter.Element("name") is null)
                {
                    Console.WriteLine($"Warning: Parameter name is null. Element: {parameter}.");
                    randomName = "unnamedParameter" + _unnamedParameters++;
                    Console.WriteLine($"Giving it name {randomName}");
                }

                var paramName = new XAttribute("name", (parameter.Element("name")?.Value ?? randomName)
                                                       ?? throw new InvalidDataException());
                
                var type = new XAttribute
                (
                    "type",
                    param
                        .Replace("const", string.Empty)
                        .Replace("struct", string.Empty)
                        .Trim()
                );

                var count = parameter.Attribute("len") != null
                    ? new XAttribute("count", parameter.Attribute("len")?.Value ?? throw new NullReferenceException())
                    : null;

                var flow = new XAttribute
                (
                    "flow",
                    param.Contains("*") && !param.Contains("const") ? "out" : "in"
                );

                p.Add(paramName, type, flow);
                if (count != null)
                {
                    p.Add(count);
                }

                if (!(parameter.Attribute("group") is null))
                {
                    p.Add(new XAttribute("group", parameter.Attribute("group")?.Value
                                                  ?? throw new InvalidDataException()));
                }

                function.Add(p);
            }

            function.Add(name);
            function.Add(returns);
            return function;
        }

19 Source : OpenCLReader.cs
with MIT License
from dotnet

public IEnumerable<Enum> ReadEnums(object obj, BindTask task)
        {
            var doc = obj as XDoreplacedent;
            Debug.replacedert(doc != null, $"{nameof(doc)} != null");

            var registry = doc.Element("registry");
            Debug.replacedert(registry != null, $"{nameof(registry)} != null");
            
            var allEnums = registry
                .Elements("enums")
                .Elements("enum")
                .DistinctBy(x => x.Attribute("name")?.Value)
                .Where
                (
                    x => x.Parent?.Attribute("name")?.Value != "Constants" &&
                         x.Parent?.Attribute("name")?.Value != "MiscNumbers"
                )
                .ToDictionary
                (
                    x => x.Attribute("name")?.Value,
                    x => FormatToken
                    (
                        x.Attribute("value")?.Value ?? (x.Attribute("bitpos") is null
                            ? null
                            : (1L << int.Parse(x.Attribute("bitpos")?.Value ?? throw new InvalidDataException())).ToString("X"))
                    )
                );
            Debug.replacedert(allEnums != null, nameof(allEnums) + " != null");
            
            var apis = registry.Elements("feature").Concat
            (
                registry.Elements("extensions").Elements("extension")
                ?? throw new InvalidDataException()
            );
            Debug.replacedert(apis != null, nameof(apis) + " != null");
            
            var removals = registry
                .Elements("feature")
                .Elements("remove")
                .Elements("enum")
                .Attributes("name")
                .Select(x => x.Value)
                .ToList();
            
            foreach (var api in apis)
            {
                foreach (var requirement in api.Elements("require"))
                {
                    var apiName = requirement.Attribute("api")?.Value ??
                                  api.Attribute("api")?.Value ??
                                  api.Attribute("supported")?.Value ??
                                  "opencl";
                    var apiVersion = api.Attribute("number") != null
                        ? Version.Parse(api.Attribute("number")?.Value ?? throw new InvalidDataException())
                        : null;
                    var tokens = requirement.Elements("enum")
                        .Attributes("name")
                        .Where(x => !Constants.ContainsKey(x.Value) && allEnums.ContainsKey(x.Value))
                        .Select
                        (
                            token => new Token
                            {
                                Attributes = removals.Contains(token.Value)
                                    ? new List<Attribute>
                                    {
                                        new Attribute
                                        {
                                            Arguments = new List<string>
                                                {$"\"Deprecated in version {apiVersion?.ToString(2)}\""},
                                            Name = "System.Obsolete"
                                        }
                                    }
                                    : new List<Attribute>(),
                                Doc = string.Empty,
                                Name = Naming.Translate(TrimName(token.Value, task), task.FunctionPrefix),
                                NativeName = token.Value,
                                Value = allEnums.ContainsKey
                                    (token.Value)
                                    ? allEnums[token.Value]
                                    : FormatToken(Constants[token.Value].ToString())
                            }
                        )
                        .ToList();
                    foreach (var name in apiName.Split('|'))
                    {
                        var ret = new Enum
                        {
                            Attributes = new List<Attribute>(),
                            ExtensionName = api.Name == "feature"
                                ? "Core"
                                : ExtensionName(api.Attribute("name")?.Value, task),
                            Name = Naming.Translate(TrimName(api.Attribute("name")?.Value, task), task.FunctionPrefix),
                            NativeName = api.Attribute("name")?.Value,
                            ProfileName = name,
                            ProfileVersion = apiVersion,
                            Tokens = tokens
                        };

                        yield return ret;
                    }
                }
            }
        }

19 Source : OpenGLReader.cs
with MIT License
from dotnet

public IEnumerable<Function> ReadFunctions(object obj, BindTask task)
        {
            var state = (State) obj;
            return state.Functions ??= CoreReadFunctions();

            IEnumerable<Function> CoreReadFunctions()
            {
                var doc = state.Doreplacedent;
                Debug.replacedert(doc != null, $"{nameof(doc)} != null");

                var registry = doc.Element("registry");
                Debug.replacedert(registry != null, $"{nameof(registry)} != null");

                var allFunctions = registry.Elements("commands")
                    .Elements("command")
                    .Select(x => TranslateCommand(x, task))
                    .ToDictionary(x => x.Attribute("name")?.Value, x => x);
                Debug.replacedert(allFunctions != null, $"{nameof(allFunctions) != null}");

                var apis = registry.Elements("feature")
                    .Concat
                    (
                        registry.Elements("extensions").Elements("extension")
                        ?? throw new InvalidDataException()
                    );
                Debug.replacedert(apis != null, $"{nameof(apis)} != null");

                var removals = registry
                    .Elements("feature")
                    .Select
                    (
                        x => (x, x.Elements("remove")
                            .Elements("command")
                            .Attributes("name")
                            .Select(y => y.Value))
                    )
                    .SelectMany
                    (
                        x => x.Item2.Select
                        (
                            y => (y,
                                Version.Parse
                                (
                                    x.x.Attribute("number")?.Value ?? throw new DataException
                                        ("Removal does not have replacedociated version")
                                ))
                        )
                    )
                    .ToDictionary();

                Debug.replacedert(removals != null, $"{nameof(removals) != null}");

                foreach (var api in apis)
                {
                    foreach (var requirement in api.Elements("require"))
                    {
                        var apiName = requirement.Attribute("api")?.Value ??
                                      api.Attribute("api")?.Value ??
                                      api.Attribute("supported")?.Value ??
                                      "gl";
                        var apiVersion = api.Attribute("number") != null
                            ? Version.Parse(api.Attribute("number")?.Value ?? throw new InvalidDataException())
                            : null;
                        foreach (var name in apiName.Split('|'))
                        {
                            foreach (var function in requirement.Elements("command")
                                .Attributes("name")
                                .Select(x => x.Value))
                            {
                                var xf = allFunctions[TrimName(function, task)];

                                var ret = new Function
                                {
                                    Attributes = removals.TryGetValue(function, out var ver) && ver > apiVersion
                                        ? new List<Attribute>
                                        {
                                            new Attribute
                                            {
                                                Name = "System.Obsolete",
                                                Arguments = new List<string>
                                                {
                                                    $"\"Deprecated in version {apiVersion?.ToString(2)}\""
                                                }
                                            }
                                        }
                                        : new List<Attribute>(),
                                    Categories = new List<string> {TrimName(api.Attribute("name")?.Value, task)},
                                    Doc = string.Empty,
                                    ExtensionName = api.Name == "feature"
                                        ? "Core"
                                        : TrimName(api.Attribute("name")?.Value, task),
                                    GenericTypeParameters = new List<GenericTypeParameter>(),
                                    Name = task.RenamedNativeNames.TryGetValue(xf.Attribute("name")!.Value, out var n)
                                        ? n
                                        : Naming.Translate
                                        (
                                            NameTrimmer
                                                .Trim
                                                (
                                                    TrimName(xf.Attribute("name")?.Value, task),
                                                    task.FunctionPrefix
                                                ), task.FunctionPrefix
                                        ),
                                    NativeName = function,
                                    Parameters = ParseParameters(xf),
                                    ProfileName = name,
                                    ProfileVersion = apiVersion,
                                    ReturnType = ParseTypeSignature
                                    (
                                        xf.Element("returns")
                                        ?? throw new InvalidDataException()
                                    )
                                };
                                
                                foreach (var param in ret.Parameters)
                                {
                                    Rename(task.RenamedNativeNames, param.Type);
                                }
                                
                                Rename(task.RenamedNativeNames, ret.ReturnType);

                                yield return ret;

                                if (api.Name == "feature" && name == "gl" && ret.Attributes.Count == 0)
                                {
                                    yield return new Function
                                    {
                                        Attributes = new List<Attribute>(),
                                        Categories = ret.Categories,
                                        Doc = ret.Doc,
                                        ExtensionName = ret.ExtensionName,
                                        GenericTypeParameters = new List<GenericTypeParameter>(),
                                        Name = ret.Name,
                                        NativeName = ret.NativeName,
                                        Parameters = ret.Parameters,
                                        ProfileName = "glcore",
                                        ProfileVersion = apiVersion,
                                        ReturnType = ret.ReturnType
                                    };
                                }

                                allFunctions.Remove(function);
                            }
                        }
                    }
                }
            }
        }

19 Source : OpenGLReader.cs
with MIT License
from dotnet

public IEnumerable<Enum> ReadEnums(object obj, BindTask task)
        {
            var state = (State) obj;
            var doc = state.Doreplacedent;
            Debug.replacedert(doc != null, nameof(doc) + " != null");

            var registry = doc.Element("registry");
            Debug.replacedert(registry != null, nameof(registry) + " != null");
            
            var allEnums = registry.Elements("enums")
                .Elements("enum")
                .DistinctBy(x => x.Attribute("name")?.Value)
                .ToDictionary
                (
                    x => x.Attribute("name")?.Value,
                    x => (FormatToken(x.Attribute("value")?.Value), x.Attribute("group")?.Value.Split(','))
                );
            
            var apis = registry.Elements("feature").Concat(registry.Elements("extensions").Elements("extension"));

            var removals = registry
                .Elements("feature")
                .Select
                (
                    x => (x, x.Elements("remove")
                        .Elements("enum")
                        .Attributes("name")
                        .Select(y => y.Value))
                )
                .SelectMany
                (
                    x => x.Item2.Select
                    (
                        y => (y,
                            Version.Parse
                            (
                                x.x.Attribute("number")?.Value ?? throw new DataException
                                    ("Removal does not have replacedociated version")
                            ))
                    )
                )
                .ToDictionary();

            var revivals = new Dictionary<string, Version>();
            foreach (var api in apis)
            {
                foreach (var requirement in api.Elements("require"))
                {
                    var apiName = requirement.Attribute("api")?.Value ??
                                  api.Attribute("api")?.Value ??
                                  api.Attribute("supported")?.Value ??
                                  "gl";
                    var apiVersion = api.Attribute("number") != null
                        ? Version.Parse(api.Attribute("number")?.Value ?? throw new InvalidDataException())
                        : null;
                    var tokens = requirement.Elements("enum")
                        .Attributes("name")
                        .Select
                        (
                            token =>
                            {
                                if (removals.TryGetValue(token.Value, out var ver))
                                {
                                    if (ver <= apiVersion)
                                    {
                                        if (!revivals.ContainsKey(token.Value) || ver > revivals[token.Value])
                                        {
                                            revivals[token.Value] = ver;
                                        }
                                    }
                                    else if (revivals.TryGetValue(token.Value, out var revVer) && ver > revVer)
                                    {
                                        revivals.Remove(token.Value);
                                    }
                                }
                                
                                return new Token
                                {
                                    Attributes = removals.TryGetValue(token.Value, out ver) && ver > apiVersion
                                        ? new List<Attribute>
                                        {
                                            new Attribute
                                            {
                                                Arguments = new List<string>
                                                    {$"\"Deprecated in version {apiVersion?.ToString(2)}\""},
                                                Name = "System.Obsolete"
                                            }
                                        }
                                        : new List<Attribute>(),
                                    Doc = string.Empty,
                                    Name = task.RenamedNativeNames.TryGetValue(token.Value, out var n)
                                        ? n
                                        : Naming.Translate(TrimName(token.Value, task), task.FunctionPrefix),
                                    NativeName = token.Value,
                                    Value = allEnums[token.Value].Item1
                                };
                            }
                        )
                        .ToList();
                    foreach (var name in apiName.Split('|'))
                    {
                        var ret = new Enum
                        {
                            Attributes = new List<Attribute>(),
                            ExtensionName = api.Name == "feature"
                                ? "Core"
                                : TrimName(api.Attribute("name")?.Value, task),
                            Name = task.RenamedNativeNames.TryGetValue(api.Attribute("name")!.Value, out var n)
                                ? n
                                : Naming.Translate(TrimName(api.Attribute("name")?.Value, task), task.FunctionPrefix),
                            NativeName = api.Attribute("name")?.Value,
                            ProfileName = name,
                            ProfileVersion = apiVersion,
                            Tokens = tokens
                        };

                        yield return ret;

                        if (api.Name == "feature" && name == "gl")
                        {
                            yield return new Enum
                            {
                                Attributes = ret.Attributes,
                                ExtensionName = ret.ExtensionName,
                                Name = ret.Name,
                                NativeName = ret.NativeName,
                                ProfileName = "glcore",
                                ProfileVersion = apiVersion,
                                Tokens = tokens.Where(x => x.Attributes.Count == 0).ToList()
                            };
                        }
                    }
                }
            }

            var groups = new Dictionary<string, List<Token>>();
            foreach (var @enum in allEnums)
            {
                if (@enum.Value.Item2 is null)
                {
                    continue;
                }

                foreach (var group in @enum.Value.Item2)
                {
                    if (groups.ContainsKey(group))
                    {
                        groups[group].Add
                        (
                            new Token
                            {
                                Attributes = removals.ContainsKey(@enum.Key) && !revivals.ContainsKey(@enum.Key)
                                    ? new List<Attribute>
                                    {
                                        new Attribute
                                        {
                                            Name = "System.Obsolete"
                                        }
                                    }
                                    : new List<Attribute>(),
                                Doc = string.Empty,
                                Name = task.RenamedNativeNames.TryGetValue(@enum.Key, out var n)
                                    ? n
                                    : Naming.Translate(TrimName(@enum.Key, task), task.FunctionPrefix),
                                NativeName = @enum.Key,
                                Value = @enum.Value.Item1
                            }
                        );
                    }
                    else
                    {
                        groups.Add
                        (
                            group, new List<Token>
                            {
                                new Token
                                {
                                    Attributes = removals.ContainsKey(@enum.Key) && !revivals.ContainsKey(@enum.Key)
                                        ? new List<Attribute>
                                        {
                                            new Attribute
                                            {
                                                Name = "System.Obsolete"
                                            }
                                        }
                                        : new List<Attribute>(),
                                    Doc = string.Empty,
                                    Name = task.RenamedNativeNames.TryGetValue(@enum.Key, out var n)
                                        ? n
                                        : Naming.Translate(TrimName(@enum.Key, task), task.FunctionPrefix),
                                    NativeName = @enum.Key,
                                    Value = @enum.Value.Item1
                                }
                            }
                        );
                    }
                }
            }

            foreach (var group in groups)
            {
                foreach (var (apiName, apiVersion) in registry
                    .Elements("feature")
                    .Select(x => (x.Attribute("api")?.Value, x.Attribute("number")?.Value))
                    .Distinct())
                {
                    var ret = new Enum
                    {
                        Name = task.RenamedNativeNames.TryGetValue(group.Key, out var n) ? n : group.Key,
                        NativeName = group.Key,
                        Attributes = new List<Attribute>(),
                        ExtensionName = "Core (Grouped)",
                        ProfileName = apiName,
                        ProfileVersion = Version.Parse(apiVersion),
                        Tokens = group.Value
                    };

                    yield return ret;

                    if (apiName == "gl")
                    {
                        yield return new Enum
                        {
                            Name = ret.Name,
                            NativeName = ret.NativeName,
                            Attributes = new List<Attribute>(),
                            ExtensionName = "Core (Grouped)",
                            ProfileName = "glcore",
                            ProfileVersion = Version.Parse(apiVersion),
                            Tokens = group.Value.Where(x => x.Attributes.Count == 0).ToList()
                        };
                    }
                }
            }
        }

19 Source : VulkanSpecification.cs
with MIT License
from dotnet

public static VulkanSpecification LoadFromXmlStream(Stream specFileStream)
        {
            var spec = XDoreplacedent.Load(specFileStream);
            var registry = spec.Element("registry");
            var commands = registry.Element("commands");
            var commandDefinitions = commands.Elements("command")
                .Select(commandx => CommandDefinition.CreateFromXml(commandx)).ToArray();

            var constantDefinitions = registry.Elements("enums")
                .Where(enumx => enumx.Attribute("name").Value == "API Constants")
                .SelectMany(enumx => enumx.Elements("enum"))
                .Select(enumxx => ConstantDefinition.CreateFromXml(enumxx)).ToArray();

            var types = registry.Elements("types");
            var typedefDefinitions = types.Elements("type").Where(xe => xe.Value.Contains("typedef") && xe.HasCategoryAttribute("bitmask"))
                .Select(xe2 => TypedefDefinition.CreateFromXml(xe2)).ToArray();

            var enumDefinitionsNoAliases = registry.Elements("enums")
                .Where(enumx => enumx.GetTypeAttributeOrNull() == "enum" || enumx.GetTypeAttributeOrNull() == "bitmask")
                .Select(enumx => EnumDefinition.CreateFromXml(enumx))
                .ToArray();

            var enumDefinitions = registry.Elements("types")
                .Elements("type")
                .Where(xe => xe.HasCategoryAttribute("enum") && !(xe.Attribute("alias") is null))
                .Select
                (
                    x => enumDefinitionsNoAliases.First(y => y.Name == x.Attribute("alias")?.Value)
                        .Clone(x.GetNameAttribute())
                )
                .Concat(enumDefinitionsNoAliases)
                .ToArray();

            var structures = types.Elements("type").Where(typex => typex.HasCategoryAttribute("struct"))
                .Select(typex => StructureDefinition.CreateFromXml(typex)).ToArray();

            var unions = 
                types.Elements("type")
                .Where(typex => typex.HasCategoryAttribute("union"))
                .Select(typex => StructureDefinition.CreateFromXml(typex)).ToArray();

            var handles = types.Elements("type").Where(typex => typex.HasCategoryAttribute("handle"))
                .Select(typex => HandleDefinition.CreateFromXml(typex)).ToArray();

            var baseTypes = types.Elements("type").Where(typex => typex.HasCategoryAttribute("basetype"))
                .ToDictionary(
                    typex => typex.GetNameElement(),
                    typex => typex.Element("type")?.Value ?? "nint");
            baseTypes["VkBool32"] = "Bool32";

            var extensions = registry.Element("extensions").Elements("extension")
                .Select(ExtensionDefinition.CreateFromXml).ToArray();

            var features = registry.Elements("feature")
                .Select(FeatureDefinition.CreateFromXml)
                .ToArray();

            return new VulkanSpecification(
                commandDefinitions, 
                constantDefinitions, 
                typedefDefinitions, 
                enumDefinitions, 
                structures,
                unions, 
                handles,
                baseTypes, 
                extensions,
                features);
        }

19 Source : OpenCLReader.cs
with MIT License
from dotnet

public IEnumerable<Struct> ReadStructs(object obj, BindTask task)
        {
            var xd = (XDoreplacedent) obj;
            
            var rawStructs = xd.Element("registry")?.Element("types")?.Elements("type")
                .Where(type => type.HasCategoryAttribute("struct"))
                .Select(StructureDefinition.CreateFromXml)
                .ToArray();
            
            var structs = ConvertStructs(rawStructs, task);
            
            foreach (var feature in xd.Element
                    ("registry")
                ?.Elements("feature")
                .Attributes("api")
                .Select(x => x.Value)
                .RemoveDuplicates() ?? throw new InvalidDataException())
            {
                foreach (var (_, s) in structs)
                {
                    yield return new Struct
                    {
                        Attributes = s.Attributes,
                        ExtensionName = "Core",
                        Fields = s.Fields,
                        Functions = s.Functions,
                        Name = s.Name,
                        NativeName = s.NativeName,
                        ProfileName = feature,
                        ProfileVersion = null
                    };
                }
            }
            
            task.TypeMaps.Add(structs.ToDictionary(x => x.Key, x => x.Value.Name));
        }

19 Source : OpenGLReader.cs
with MIT License
from dotnet

private XElement TranslateCommand(XContainer command, BindTask task)
        {
            var function = new XElement("function");

            var cmdName = FunctionName(command, task);
            var name = new XAttribute("name", cmdName);

            var returnsAttributes = new List<XAttribute>();
            returnsAttributes.Add(new XAttribute
            (
                "type",
                FunctionParameterType(command.Element("proto"))
                    .Replace("const", string.Empty)
                    .Replace("struct", string.Empty)
                    .Replace("String *", "String")
                    .Trim()
            ));

            if (command.Element("proto")?.Attribute("group") is not null)
            {
                returnsAttributes.Add
                (
                    new XAttribute
                    (
                        "group", command.Element("proto")?.Attribute("group")?.Value
                                 ?? throw new InvalidDataException()
                    )
                );
            }

            if (command.Element("proto")?.Attribute("clreplaced") is not null)
            {
                returnsAttributes.Add
                (
                    new XAttribute
                    (
                        "clreplaced", command.Element("proto")?.Attribute("clreplaced")?.Value
                                 ?? throw new InvalidDataException()
                    )
                );
            }
            
            var returns = new XElement
            (
                "returns",
                returnsAttributes.Cast<object>().ToArray()
            );

            foreach (var parameter in command.Elements("param"))
            {
                var param = FunctionParameterType(parameter);

                var p = new XElement("param");
                var paramName = new XAttribute("name", parameter.Element("name")?.Value
                                                       ?? throw new NullReferenceException());
                
                var type = new XAttribute
                (
                    "type",
                    param
                        .Replace("const", string.Empty)
                        .Replace("struct", string.Empty)
                        .Trim()
                );

                var count = parameter.Attribute("len") != null
                    ? new XAttribute("count", parameter.Attribute("len")?.Value ?? throw new NullReferenceException())
                    : null;

                var flow = new XAttribute
                (
                    "flow",
                    param.Contains("*") && !param.Contains("const") ? "out" : "in"
                );

                p.Add(paramName, type, flow);
                if (count != null)
                {
                    p.Add(count);
                }

                if (!(parameter.Attribute("group") is null))
                {
                    p.Add(new XAttribute("group", parameter.Attribute("group")?.Value
                                                  ?? throw new InvalidDataException()));
                }

                if (!(parameter.Attribute("clreplaced") is null))
                {
                    p.Add(new XAttribute("clreplaced", parameter.Attribute("clreplaced")?.Value
                                                  ?? throw new InvalidDataException()));
                }

                function.Add(p);
            }

            function.Add(name);
            function.Add(returns);
            return function;
        }

19 Source : FeatureDefinition.cs
with MIT License
from dotnet

public static FeatureDefinition CreateFromXml(XElement xe)
        {
            var name = xe.GetNameAttribute();
            var numberString = xe.Attribute("number")?.Value ?? throw new InvalidDataException();
            var number = Version.Parse(numberString);
            var api = xe.Attribute("api")?.Value;
            var enumNames = new List<string>();
            var commandNames = new List<string>();
            var typeNames = new List<string>();
            var enumExtensionValues = new List<EnumExtensionValue>();

            foreach (var require in xe.Elements("require"))
            {
                enumNames.AddRange(require.Elements("enum")
                    .Select(x => ParseEnumRequirement(x, 0, enumExtensionValues)));
                
                commandNames.AddRange(require.Elements("command")
                    .Select(x => x.GetNameAttribute()));

                commandNames.AddRange(require.Elements("type")
                    .Select(x => x.GetNameAttribute()));
            }

            return new FeatureDefinition
            (
                name, number, api, enumNames.ToArray(), commandNames.ToArray(), typeNames.ToArray(),
                enumExtensionValues.ToArray()
            );
        }

19 Source : HandleDefinition.cs
with MIT License
from dotnet

public static HandleDefinition CreateFromXml(XElement xe)
        {
            Require.NotNull(xe);

            if (!(xe.Attribute("alias") is null))
            {
                Debug.replacedert(xe.Doreplacedent != null, "xe.Doreplacedent != null");
                var ret = CreateFromXml
                (
                    xe.Doreplacedent.Element("registry")?
                        .Elements("types")
                        .Elements("type")
                        .Where(type => type.HasCategoryAttribute("handle"))
                        .FirstOrDefault(x => x.GetNameElementOrNull() == xe.Attribute("alias")?.Value) ?? throw new Exception("wat")
                );
                
                return new HandleDefinition(xe.GetNameAttribute(), ret.CanBeDispatched, ret.Parent);
            }
            
            var name = xe.GetNameElement();
            var canBeDispatched = xe.GetTypeElement() == "VK_DEFINE_HANDLE";
            var parent = xe.Attribute("parent")?.Value;

            return new HandleDefinition(name, canBeDispatched, parent);
        }

19 Source : StructureDefinition.cs
with MIT License
from dotnet

public static StructureDefinition CreateFromXml(XElement xe)
        {
            Require.NotNull(xe);

            if (!(xe.Attribute("alias") is null))
            {
                var ret = CreateFromXml
                (
                    xe.Doreplacedent.Element("registry")
                        .Elements("types")
                        .Elements("type")
                        .Where(typex => typex.HasCategoryAttribute("struct"))
                        .FirstOrDefault(x => x.GetNameAttribute() == xe.Attribute("alias").Value) ?? throw new Exception("wat")
                );
                
                return new StructureDefinition(xe.GetNameAttribute(), ret.Members);
            }

            var name = xe.GetNameAttribute();
            var members = xe.Elements
                    ("member")
                .Where(x => !(x.Element("name") is null))
                .Select(memberx => MemberSpec.CreateFromXml(memberx))
                .ToArray();
            return new StructureDefinition(name, members);
        }

19 Source : ConnectionStringsConfigUpdater.cs
with MIT License
from dotnet

public Task<IUpdaterResult> IsApplicableAsync(IUpgradeContext context, ImmutableArray<ConfigFile> inputs, CancellationToken token)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Find connectionStrings elements in the config files
            var connectionStrings = new Dictionary<string, string>();
            foreach (var configFile in inputs)
            {
                var connectionStringsElement = configFile.Contents.XPathSelectElement(ConnectionStringsPath);
                if (connectionStringsElement is not null)
                {
                    foreach (var connectionString in connectionStringsElement.Elements(AddConnectionStringElementName))
                    {
                        if (connectionString is not null)
                        {
                            var key = connectionString.Attribute(NameAttributeName);
                            var value = connectionString.Attribute(ConnectionStringAttributeName);
                            if (key is not null && value is not null)
                            {
                                _logger.LogDebug("Found connection string {ConnectionStringName} in {ConfigFilePath}", key.Value, configFile.Path);
                                connectionStrings[key.Value] = value.Value;
                            }
                        }
                    }
                }
            }

            var jsonConfigFiles = FindExistingAppSettingsFiles(context);

            // Check for existing appSettings.json files for connection strings
            foreach (var setting in connectionStrings)
            {
                if (!jsonConfigFiles.Any(s => !string.IsNullOrEmpty(s.Configuration.GetConnectionString(setting.Key))))
                {
                    _connectionStrings[setting.Key] = setting.Value;
                }
                else
                {
                    _logger.LogDebug("Existing app settings already include connection string {ConnectionStringName}", setting.Key);
                }
            }

            _logger.LogInformation("Found {ConnectionStringsCount} connection strings for upgrade: {ConnectionStringNames}", _connectionStrings.Count, string.Join(", ", _connectionStrings.Keys));

            var result = _connectionStrings.Count > 0;

            return Task.FromResult<IUpdaterResult>(new DefaultUpdaterResult(result));
        }

19 Source : AppSettingsConfigUpdater.cs
with MIT License
from dotnet

public Task<IUpdaterResult> IsApplicableAsync(IUpgradeContext context, ImmutableArray<ConfigFile> inputs, CancellationToken token)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Find appSettings elements in the config files
            var appSettings = new Dictionary<string, string>();
            foreach (var configFile in inputs)
            {
                var appSettingsElement = configFile.Contents.XPathSelectElement(AppSettingsPath);
                if (appSettingsElement is not null)
                {
                    foreach (var setting in appSettingsElement.Elements(AddSettingElementName))
                    {
                        if (setting is not null)
                        {
                            var key = setting.Attribute(KeyAttributeName);
                            var value = setting.Attribute(ValueAttributeName);
                            if (key is not null && value is not null)
                            {
                                _logger.LogDebug("Found app setting {AppSettingName} in {ConfigFilePath}", key.Value, configFile.Path);
                                appSettings[key.Value] = value.Value;
                            }
                        }
                    }
                }
            }

            var jsonConfigFiles = FindExistingAppSettingsFiles(context);

            // Check for existing appSettings.json files for app settings
            foreach (var setting in appSettings)
            {
                if (!jsonConfigFiles.Any(s => !string.IsNullOrEmpty(s.Configuration[setting.Key])))
                {
                    _appSettings[setting.Key] = setting.Value;
                }
                else
                {
                    _logger.LogDebug("Existing app settings already include setting {SettingName}", setting.Key);
                }
            }

            _logger.LogInformation("Found {AppSettingCount} app settings for upgrade: {AppSettingNames}", _appSettings.Count, string.Join(", ", _appSettings.Keys));

            var result = _appSettings.Count > 0;

            return Task.FromResult<IUpdaterResult>(new DefaultUpdaterResult(result));
        }

19 Source : WebNamespaceConfigUpdater.cs
with MIT License
from dotnet

public Task<IUpdaterResult> IsApplicableAsync(IUpgradeContext context, ImmutableArray<ConfigFile> inputs, CancellationToken token)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Find namespace imports in config files
            var namespaces = new List<string>();
            foreach (var configFile in inputs)
            {
                var namespacesElement = configFile.Contents.XPathSelectElement(NamespacesPath);
                if (namespacesElement is not null)
                {
                    foreach (var ns in namespacesElement.Elements(AddElementName))
                    {
                        if (ns is not null)
                        {
                            var nsName = ns.Attribute(NamespaceAttributeName);
                            if (nsName is not null)
                            {
                                var nsNameValue = nsName.Value;
                                _logger.LogDebug("Found namespace {NamespaceName} in {ConfigFilePath}", nsNameValue, configFile.Path);
                                if (NamespacesToDrop.Any(s => nsNameValue.Equals(s, StringComparison.Ordinal) || nsNameValue.StartsWith($"{s}.", StringComparison.Ordinal)))
                                {
                                    _logger.LogDebug("Not upgrading namespace {NamespaceName}", nsNameValue);
                                }
                                else
                                {
                                    namespaces.Add(nsNameValue);
                                }
                            }
                        }
                    }
                }
            }

            _logger.LogDebug("Found {NamespaceCount} namespaces imported into web pages in config files", namespaces.Count);

            var project = context.CurrentProject.Required();

            var alreadyImportedNamespaces = new List<string>();
            _viewImportsPath = project.FindFiles(ViewImportsRelativePath, ProjecreplacedemType.Content).FirstOrDefault();

            // Look for a _ViewImports.cstml to see whether any of the namespaces are already imported
            if (_viewImportsPath is null)
            {
                _logger.LogDebug("No _ViewImports.cshtml found in project");
            }
            else
            {
                alreadyImportedNamespaces.AddRange(File.ReadAllLines(_viewImportsPath)
                    .Select(line => line.Trim())
                    .Where(line => line.StartsWith(RazorUsingPrefix, StringComparison.Ordinal))
                    .Select(line => line.Substring(RazorUsingPrefix.Length).Trim()));

                _logger.LogDebug("Found {NamespaceCount} namespaces already in _ViewImports.cshtml", alreadyImportedNamespaces.Count);
            }

            _namespacesToUpgrade = namespaces.Distinct().Where(ns => !alreadyImportedNamespaces.Contains(ns));
            _logger.LogInformation("{NamespaceCount} web page namespace imports need upgraded: {Namespaces}", _namespacesToUpgrade.Count(), string.Join(", ", _namespacesToUpgrade));
            return Task.FromResult<IUpdaterResult>(new DefaultUpdaterResult(_namespacesToUpgrade.Any()));
        }

19 Source : WindowsUtilities.cs
with MIT License
from dotnet

public string GetElementFromAppConfig(string configPath, string configuration, string key)
        {
            if (File.Exists(configPath))
            {
                var configFile = new ConfigFile(configPath);
                var configElement = configFile.Contents.XPathSelectElement(configuration);
                if (configElement is not null)
                {
                    var hdpi = configElement.Elements("add").Where(e => e.Attribute("key").Value == key).FirstOrDefault();
                    if (hdpi is not null)
                    {
                        return hdpi.Attribute("value").Value;
                    }
                }
            }

            return string.Empty;
        }

19 Source : mcwpf.cs
with MIT License
from dotnet

static void GenerateCode(XDoreplacedent doc, StreamWriter stream, string indent, string keyword)
        {
            IndentedTextWriter writer = new IndentedTextWriter(stream, indent);
            writer.Indent = 1;
            var providers = doc.Root.Elements(ns + "instrumentation").Elements(ns + "events").Elements(ns + "provider");

            // Built in levels
            var builtInLevels = new XElement[] {
                new XElement("level", new XAttribute("symbol", "LogAlways"), new XAttribute("value", 0)),
                new XElement("level", new XAttribute("symbol", "Critical"), new XAttribute("value", 1)),
                new XElement("level", new XAttribute("symbol", "Error"), new XAttribute("value", 2)),
                new XElement("level", new XAttribute("symbol", "Warning"), new XAttribute("value", 3)),
                new XElement("level", new XAttribute("symbol", "Info"), new XAttribute("value", 4)),
                new XElement("level", new XAttribute("symbol", "Verbose"), new XAttribute("value", 5)) };

            // Write Levels enum
            var levels = providers.Elements(ns + "levels").Elements(ns + "level");
            levels = builtInLevels.Concat(levels);
            WriteEnum("Level : byte", writer, levels, "symbol", "value", false);

            // Write Keywords enum
            var keywords = providers.Elements(ns + "keywords").Elements(ns + "keyword");
            WriteEnum("Keyword", writer, keywords, "symbol", "mask", true);

            var builtInOpcodes = new XElement[] {
                new XElement("opcode", new XAttribute("name", "win:Info"), new XAttribute("symbol", "Info"), new XAttribute("value", 0)),
                new XElement("opcode", new XAttribute("name", "win:Start"), new XAttribute("symbol", "Start"), new XAttribute("value", 1)),
                new XElement("opcode", new XAttribute("name", "win:Stop"), new XAttribute("symbol", "Stop"), new XAttribute("value", 2)),
                new XElement("opcode", new XAttribute("name", "win:DC_Start"), new XAttribute("symbol", "DC_Start"), new XAttribute("value", 3)),
                new XElement("opcode", new XAttribute("name", "win:DC_Stop"), new XAttribute("symbol", "DC_Stop"), new XAttribute("value", 4)),
                new XElement("opcode", new XAttribute("name", "win:Extension"), new XAttribute("symbol", "Extension"), new XAttribute("value", 5)),
                new XElement("opcode", new XAttribute("name", "win:Reply"), new XAttribute("symbol", "Reply"), new XAttribute("value", 6)),
                new XElement("opcode", new XAttribute("name", "win:Resume"), new XAttribute("symbol", "Resume"), new XAttribute("value", 7)),
                new XElement("opcode", new XAttribute("name", "win:Suspend"), new XAttribute("symbol", "Suspend"), new XAttribute("value", 8)),
                new XElement("opcode", new XAttribute("name", "win:Transfer"), new XAttribute("symbol", "Transfer"), new XAttribute("value", 9)),
            };

            // Write Opcode enum
            var opcodes = providers.Descendants(ns + "opcode");
            opcodes = builtInOpcodes.Concat(opcodes);
            // Enum values are used by value and never referenced.
            // WriteEnum("Opcode : byte", writer, opcodes, "symbol", "value", false);

            // Write Event enum
            var eventsFlat = providers.Elements(ns + "events").Elements(ns + "event");
            if (!string.IsNullOrEmpty(keyword))
            {
                eventsFlat = eventsFlat.Where((element) => element.Attribute("keywords").Value.Split(' ').Contains(keyword));
            }
            WriteEnum("Event : ushort", writer, eventsFlat, "symbol", "value", false);

            // A function to map an Event to a GUID
            var tasks = providers.Elements(ns + "tasks").Elements(ns + "task");
            var events = from e in eventsFlat
                          join t in tasks on e.Attribute("task").Value equals t.Attribute("name").Value
                          select new
                          {
                              Symbol     = e.Attribute("symbol").Value,
                              Value      = e.Attribute("value").Value,
                              Guid       = new Guid(t.Attribute("eventGUID").Value),
                              Task       = t.Attribute("value").Value,
                              TaskSymbol = t.Attribute("symbol").Value,
                              Opcode     = e.Attribute("opcode").Value,
                              Version    = e.Attribute("version").Value,
                              Keywords   = e.Attribute("keywords").Value,
                          };

            /*
             * Write out a function to map the Event to the task GUID
             *
             * internal Guid GuidForEvent(Event evt)
             * {
             *  switch(evt)
             *  {
             *      case Event.A: return new Guid(...); break;
             *      default: throw ArgumentException();
             *  }
             * }
             */
            WriteMapFunction("GetGuidForEvent", "Guid", "Event", writer, events, (e) => "Event." + e.Symbol, (e) => "// " + e.Guid, (e) =>
            {
                byte[] bytes = e.Guid.ToByteArray();
                Int32 intPart = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
                short shortPart1 = (short)(bytes[5] << 8 | bytes[4]);
                short shortPart2 = (short)(bytes[7] << 8 | bytes[6]);
                return string.Format("return new Guid(0x{0:X}, 0x{1:X}, 0x{2:X}, 0x{3:X}, 0x{4:X}, 0x{5:X}, 0x{6:X}, 0x{7:X}, 0x{8:X}, 0x{9:X}, 0x{10:X});",
                            intPart, shortPart1, shortPart2, bytes[8], bytes[9], bytes[0xA], bytes[0xB], bytes[0xC], bytes[0xD], bytes[0xE], bytes[0xF]);
            });

            // GetTaskForEvent - Map Event => Task ID
            WriteMapFunction("GetTaskForEvent", "ushort", "Event", writer, events, (e) => "Event." + e.Symbol, (e) => String.Empty, (e) => string.Format("return {0};", e.Task));

            // GetOpcodeForEvent - Map Event => Opcode
            Dictionary<string, int> OpcodeMap = new Dictionary<string, int>();
            foreach (var op in opcodes)
            {
                OpcodeMap[op.Attribute("name").Value] = Int32.Parse(op.Attribute("value").Value);
            }
            WriteMapFunction("GetOpcodeForEvent", "byte", "Event", writer, events.OrderBy(e => OpcodeMap[e.Opcode]), (e) => "Event." + e.Symbol, (e) => String.Empty, (e) => string.Format("return {0};", OpcodeMap[e.Opcode]));

            // GetVersionForEvent - Map Event => Version
            WriteMapFunction("GetVersionForEvent", "byte", "Event", writer, events.OrderBy(e => Int32.Parse(e.Version)), (e) => "Event." + e.Symbol, (e) => String.Empty, (e) => string.Format("return {0};", e.Version));

            // We could generate 1 switch instead of 3, but in my test this resulted in 18k of o code instead of 4k for all 3 methods.
            // Since switching on a consecutive integer range should be close to O(1) smaller code is the better option.  We also avoid the Array allocation.
            // WriteMapFunction("GetEventData", "int[]", "Event", writer, events, (e) => "Event." + e.Symbol, (e) => String.Empty, (e) => string.Format("return new int[] {{{0}, {1}, {2}}};", e.Task, OpcodeMap[e.Opcode], e.Version));



            // Check for a common error.  This can cause build breaks.
            foreach(var error in from e in events where e.Symbol == e.TaskSymbol select e)
            {
                using (new ColorConsole(ConsoleColor.Red))
                {
                    Console.WriteLine("\nError: event {0} (ID:{1}) has the same symbol as task {2} (ID:{3}).",
                        error.Symbol, error.Value, error.TaskSymbol, error.Task);
                }
            }
        }

19 Source : AndroidXMLConverter.cs
with MIT License
from DotNetPlus

private static IEnumerable<ReswItem> ExtractAndroidItems(string sourcePath)
        {
            var sourceAndroidXML = XDoreplacedent.Load(sourcePath);
            var xmlRoot = sourceAndroidXML.Root;
            string currentComment = null;
            foreach (var xNode in xmlRoot.Nodes())
            {
                switch (xNode)
                {
                    case XComment commentNode:
                        {
                            currentComment = RemoveAntislash(commentNode.Value.Trim());
                        }
                        break;
                    case XElement elementNode:
                        {
                            switch (elementNode.Name.LocalName.ToLower())
                            {
                                case "string":
                                    {
                                        var name = elementNode.Attribute("name")?.Value;
                                        if (name != null)
                                        {
                                            var value = elementNode.Value;
                                            yield return new ReswItem(name, RemoveAntislash(value), currentComment);
                                        }
                                        break;
                                    }
                                case "plurals":
                                    {
                                        var name = elementNode.Attribute("name").Value;
                                        foreach (var subItem in elementNode.Elements("item"))
                                        {
                                            var quanreplacedy = subItem.Attribute("quanreplacedy")?.Value;
                                            if (quanreplacedy != null)
                                            {
                                                yield return new ReswItem($"{name}_{UpperCaseFirstLetter(quanreplacedy)}", RemoveAntislash(subItem.Value), currentComment);
                                            }
                                        }
                                        break;
                                    }
                            }
                            currentComment = null;
                        }
                        break;
                }
            }
        }

19 Source : SIPEventDialogInfo.cs
with BSD 2-Clause "Simplified" License
from double-hi

public override void Load(string dialogInfoXMLStr)
        {
            try
            {
                XNamespace ns = m_dialogXMLNS;
                XDoreplacedent eventDialogDoc = XDoreplacedent.Parse(dialogInfoXMLStr);

                Version = Convert.ToInt32(((XElement)eventDialogDoc.FirstNode).Attribute("version").Value);
                State = (SIPEventDialogInfoStateEnum)Enum.Parse(typeof(SIPEventDialogInfoStateEnum), ((XElement)eventDialogDoc.FirstNode).Attribute("state").Value, true);
                Enreplacedy = SIPURI.ParseSIPURI(((XElement)eventDialogDoc.FirstNode).Attribute("enreplacedy").Value);

                var dialogElements = eventDialogDoc.Root.Elements(ns + "dialog");
                foreach (XElement dialogElement in dialogElements)
                {
                    DialogItems.Add(SIPEventDialog.Parse(dialogElement));
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPEventDialogInfo Ctor. " + excp.Message);
                throw;
            }
        }

19 Source : SIPEventPresence.cs
with BSD 2-Clause "Simplified" License
from double-hi

public override void Load(string presenceXMLStr)
        {
            try
            {
                XNamespace ns = m_pidfXMLNS;
                XDoreplacedent presenceDoc = XDoreplacedent.Parse(presenceXMLStr);

                Enreplacedy = SIPURI.ParseSIPURI(((XElement)presenceDoc.FirstNode).Attribute("enreplacedy").Value);

                var tupleElements = presenceDoc.Root.Elements(ns + "tuple");
                foreach (XElement tupleElement in tupleElements)
                {
                    Tuples.Add(SIPEventPresenceTuple.Parse(tupleElement));
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPEventPresence Load. " + excp.Message);
                throw;
            }
        }

19 Source : Chart.cs
with GNU General Public License v3.0
from DSorlov

public void AddSeries(Series series)
        {
            if (ChartXml.Elements(XName.Get("ser", DocX.c.NamespaceName)).Count() == MaxSeriesCount)
                throw new InvalidOperationException("Maximum series for this chart is" + MaxSeriesCount.ToString() + "and have exceeded!");
            ChartXml.Add(series.Xml);
        }

19 Source : _Extensions.cs
with GNU General Public License v3.0
from DSorlov

public static void Flatten(this XElement e, XName name, List<XElement> flat)
        {
            // Add this element (without its children) to the flat list.
            XElement clone = CloneElement(e);
            clone.Elements().Remove();

            // Filter elements using XName.
            if (clone.Name == name)
                flat.Add(clone);

            // Process the children.
            if (e.HasElements)
                foreach (XElement elem in e.Elements(name)) // Filter elements using XName
                    elem.Flatten(name, flat);
        }

19 Source : PointCloudLoader.cs
with GNU Lesser General Public License v3.0
from Edgar077

public PointCloud Load()
		{
			// Vertices
			var positionId = mesh
				.Element($"{ns}vertices")
				.Element($"{ns}input")
				.Attribute("source").Value.TrimStart(new[]{ '#' });

			var polylist = readVecArray<Vector3>(mesh, positionId);
			foreach(var poly in polylist)
				Vertices.Add(new VertexForCollada(System.Convert.ToUInt32(Vertices.Count), poly));

			// Normals
			var normals = mesh
				.Element($"{ns}polylist")
				.Elements($"{ns}input").FirstOrDefault(x => x.Attribute("semantic").Value == "NORMAL");
			if (normals != null) {
				var normalId = normals.Attribute("source").Value.TrimStart(new[]{ '#' });

				Normals = new List<Vector3>();
				Normals = readVecArray<Vector3>(mesh, normalId);
			}

			// Textures
			var texCoords = mesh
				.Element($"{ns}polylist")
				.Elements($"{ns}input").FirstOrDefault(x => x.Attribute("semantic").Value == "TEXCOORD");
			if (texCoords != null)
            {
				var texCoordId = texCoords.Attribute("source").Value.TrimStart(new[]{ '#' });

				Textures = new List<Vector2>();
               	Textures = readVecArray<Vector2>(mesh, texCoordId);
			}

			// Colors
			var colors = mesh
				.Element($"{ns}polylist")
				.Elements($"{ns}input").FirstOrDefault(x => x.Attribute("semantic").Value == "COLOR");
			if (colors != null) {
				var colorId = colors.Attribute("source").Value.TrimStart(new[]{ '#' });

				Colors = new List<Vector3>();
				Colors = readVecArray<Vector3>(mesh, colorId);
			}

			replacedembleVertices(mesh);
			removeUnusedVertices();

			return convertDataToArrays();
		}

19 Source : PointCloudLoader.cs
with GNU Lesser General Public License v3.0
from Edgar077

private List<T> readVecArray<T>(XElement mesh, string id)
		{
			var data = mesh
				.Elements($"{ns}source").FirstOrDefault(x => x.Attribute("id").Value == id)
				.Element($"{ns}float_array");

			var count = int.Parse(data.Attribute("count").Value);
			var array = parseFloats(data.Value);
			var result = new List<T>();

			if(typeof(T) == typeof(Vector3))
				for (var i = 0; i < count / 3; i++) 
					result.Add((T)(object)new Vector3(
						array[i * 3] ,
						array[i * 3 + 2],
						array[i * 3 + 1]
					));
			else if(typeof(T) == typeof(Vector2))
				for (var i = 0; i < count / 2; i++) 
					result.Add((T)(object)new Vector2(
						array[i * 2],
						array[i * 2 + 1]
					));
			
			return result;
		}

19 Source : PointCloudLoader.cs
with GNU Lesser General Public License v3.0
from Edgar077

private void replacedembleVertices(XElement mesh)
        {
            var poly = mesh.Element($"{ns}polylist");
            var typeCount = poly.Elements($"{ns}input").Count();
            //EDGAR TODO
            ////get infos from the elements:
            // < input semantic = "VERTEX" source = "#Cube-mesh-vertices" offset = "0" />
            //   < input semantic = "NORMAL" source = "#Cube-mesh-normals" offset = "1" />
            //   < input semantic = "COLOR" source = "#Cube-mesh-colors-Col" offset = "2" set = "0" />

               List <uint> id = parseUInts(poly.Element($"{ns}p").Value);

            for (int i = 0; i < id.Count / typeCount; i++)
            {
                uint textureIndex = uint.MaxValue;
                uint colorIndex = uint.MaxValue;

                var index = 0;

                var posIndex = id[i * typeCount + index];
                index++;


                
                var normalIndex = id[i * typeCount + index];
                index++;


                //if (Textures != null)
                //    textureIndex = id[i * typeCount + index];
                //index++;


                if (Colors != null)
                    colorIndex = id[i * typeCount + index];
                index++;


                processVertex(System.Convert.ToUInt32(posIndex), System.Convert.ToUInt32(normalIndex), System.Convert.ToUInt32(textureIndex), System.Convert.ToUInt32(colorIndex));
            }
        }

19 Source : RegisterCodeGenerator.cs
with MIT License
from emmellsoft

public string Generate()
        {
            var code = new CodeWriter(this);
            code.AppendCommentLine("=============================================================");
            code.AppendCommentLine("This code file is autogenerated. Do not modify it manually!");
            code.AppendCommentLine("=============================================================");
            code.AppendLine();


            XElement registersNode = _registersXml.Element("Registers");
            var ns = registersNode?.Attribute("namespace")?.Value ?? "missing.namespace";

            code.AppendLine("using System;");
            code.AppendLine();
            code.AppendLine("namespace " + ns);
            code.AppendLine("{");
            code.Indent++;

            XElement[] registerGroupElements = registersNode?.Elements("RegisterGroup").ToArray() ?? new XElement[0];

            Iterate(registerGroupElements, (registerGroupElement, isLastGroup) =>
            {
                string prefix = registerGroupElement.Attribute("prefix")?.Value ?? string.Empty;

                XElement[] registerElements = registerGroupElement.Elements("Register")
                    .OrderBy(GetRegisterAddress)
                    .ToArray();

                GenerateRegisterAddressEnum(code, prefix, registerElements);
                GenerateAbstractRegister(code, prefix);

                Iterate(registerElements, (registerElement, isLastRegister) =>
                {
                    GenerateRegister(code, prefix, registerElement);

                    if (!isLastGroup || !isLastRegister)
                    {
                        code.AppendLine();
                    }
                });
            });

            code.Indent--;
            code.AppendLine("}");

            return code.GetAllCode();
        }

19 Source : RegisterCodeGenerator.cs
with MIT License
from emmellsoft

private void GenerateEnum(
            CodeWriter code,
            RegisterMode registerMode,
            int registerLength,
            List<RegisterProperty> properties,
            XElement element,
            bool isFlags)
        {
            string name = GetName(element);
            string enumName = name + "Enum";

            int byteIndex;
            var bitsRange = GetBitsRange(element, registerLength, null, out byteIndex);

            EnumValue[] enumValues = element.Elements("Value")
                .Select(GetEnumValue)
                .OrderBy(x => x.Value)
                .ToArray();

            switch (registerMode)
            {
                case RegisterMode.ReadWrite:
                    if (enumValues.Count(x => x.IsDefault) != 1)
                    {
                        throw new Exception("Exactly one default enum value expected: " + name);
                    }
                    break;

                case RegisterMode.ReadClear:
                case RegisterMode.ReadOnly:
                    if (enumValues.Count(x => x.IsDefault) != 0)
                    {
                        throw new Exception("No default enum value expected: " + name);
                    }
                    break;
            }

            GenerateDescription(code, GetDescription(element));

            //code.AppendLine(bitsRange.FromBits == bitsRange.ToBits
            //    ? $"[BitMask({bitsRange.FromBits})]"
            //    : $"[BitMask({bitsRange.FromBits}, {bitsRange.ToBits})]");

            string integerType = GetIntegerType(bitsRange);

            if (isFlags)
            {
                code.AppendLine("[Flags]");
            }

            code.AppendLine($"public enum {enumName} : {integerType}");
            code.AppendLine("{");
            code.Indent++; // Enum values

            bool isFirst = true;
            Iterate(enumValues, (enumValue, isLast) =>
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else if (!string.IsNullOrEmpty(enumValue.Description))
                {
                    code.AppendLine();
                }

                byte value = enumValue.Value;
                //byte value = (byte)(enumValue.Value << bitsRange.FromBits);

                GenerateDescription(code, enumValue.Description);
                code.AppendLine($"{enumValue.Name} = {ToHex(value, 2)}{(isLast ? string.Empty : ",")}");
            });

            code.Indent--; // Enum values
            code.AppendLine("}");
            code.AppendLine();

            string defaultValue;
            if (registerMode == RegisterMode.ReadWrite)
            {
                defaultValue = enumName + "." + enumValues.Single(x => x.IsDefault).Name;
            }
            else
            {
                defaultValue = null;
            }

            Action<CodeWriter, string[]> appendPropertyreplacedigmentFromBytes = (codeWriter, byteParameterNames) =>
            {
                var composedValue = GetComposedValue(bitsRange, registerLength, byteIndex, byteParameterNames);
                codeWriter.AppendLine($"{name} = ({enumName})Enum.ToObject(typeof({enumName}), {composedValue});");
            };

            Func<string[]> getByteIndexAsByteStrings = () =>
                GetDecomposedValues(name, bitsRange, registerLength, byteIndex, false);

            properties.Add(new RegisterProperty(
                PropertyType.Enum,
                registerMode,
                name,
                GetLocalName(name),
                enumName,
                defaultValue,
                GetDescription(element),
                (codeWriter, paramName) => { },
                appendPropertyreplacedigmentFromBytes,
                getByteIndexAsByteStrings,
                byteIndex));
        }

19 Source : XElementExtensions.cs
with Apache License 2.0
from episerver

public static IEnumerable<XElement> GetChildren(this XElement xElement, string childElementName)
        {
            if (xElement == null || xElement.IsEmpty)
            {
                return Enumerable.Empty<XElement>();
            }
            return xElement.Elements(childElementName);
        }

19 Source : GLParser.cs
with MIT License
from EvergineTeam

public static GLParser FromFile(string xmlFile, params string[] Api)
        {
            XDoreplacedent file = XDoreplacedent.Load(xmlFile);
            GLParser spec = new GLParser();
            spec.HeaderComment = file.Root.Element("comment").Value;

            foreach (var feature in file.Root.Elements("feature"))
            {
                var apiName = feature.Attribute("api").Value;
                if (Api.Contains(apiName))
                {
                    var version = new GLVersion
                    {
                        Api = feature.Attribute("api").Value.ToUpper(),
                        Number = feature.Attribute("number").Value,
                    };

                    version.Name = version.Api + version.Number.Replace(".", "");

                    // Add all enums and commands from previus versions
                    int i = spec.Versions.Count - 1;
                    if (i >= 0)
                    {
                        var previousVersion = spec.Versions[i];

                        foreach (var g in previousVersion.Groups)
                        {
                            version.Groups.Add(g.Clone());
                        }

                        foreach (var c in previousVersion.Commands)
                        {
                            version.Commands.Add(c.Clone());
                        }
                    }

                    // Include all new enums and commands
                    foreach (var require in feature.Elements("require"))
                    {
                        foreach (var enumElem in require.Elements("enum"))
                        {
                            var enumName = enumElem.Attribute("name").Value;

                            // if enum doesn't exists
                            bool exists = version.Groups.Exists(g => g.Enums.Exists(e => e.Name == enumName));

                            if (!exists)
                            {
                                // Find group
                                string groupFound = FindGroupInXML(file, enumName);

                                // The group already exists
                                GlGroup glgroup = version.Groups.Find(g => g.Name == groupFound);

                                if (glgroup == null)
                                {
                                    glgroup = new GlGroup() { Name = groupFound };
                                    version.Groups.Add(glgroup);
                                }

                                // Create new Enum
                                var glEnum = new GLEnum();
                                glEnum.Initialize(file, enumName);
                                glgroup.Enums.Add(glEnum);
                            }
                        }

                        foreach (var commandElem in require.Elements("command"))
                        {
                            var glCommand = new GLCommand() { Name = commandElem.Attribute("name").Value };
                            if (version.Commands.Find(c => c.Name == glCommand.Name) == null)
                            {
                                // Create new command
                                glCommand.Initialize(commandElem.Doreplacedent);
                                version.Commands.Add(glCommand);
                            }
                        }
                    }

                    // Add enum from commands
                    foreach (var commandElem in version.Commands)
                    {
                        // Return Type
                        if (commandElem.ReturnType.Type == "GLenum")
                        {
                            var selectedGroup = commandElem.ReturnType.Group;
                            bool groupExists = version.Groups.Exists(g => g.Name == selectedGroup);
                            if (!groupExists)
                            {
                                foreach (var group in file.Root.Element("groups").Elements("group"))
                                {
                                    string groupName = group.Attribute("name").Value;
                                    if (groupName == selectedGroup)
                                    {
                                        GlGroup glgroup = new GlGroup() { Name = selectedGroup };
                                        foreach (var e in group.Elements("enum"))
                                        {
                                            GLEnum glEnum = new GLEnum();
                                            var enumName = e.Attribute("name").Value;
                                            glEnum.Initialize(file, enumName);
                                            glgroup.Enums.Add(glEnum);
                                        }
                                        version.Groups.Add(glgroup);
                                    }
                                }
                            }
                        }

                        // Parameters
                        foreach (var param in commandElem.Parameters)
                        {
                            if (param.Type == "GLenum")
                            {
                                bool groupExists = version.Groups.Exists(g => g.Name == param.Group);
                                if (!groupExists)
                                {
                                    foreach (var group in file.Root.Element("groups").Elements("group"))
                                    {
                                        string groupName = group.Attribute("name").Value;
                                        if (groupName == param.Group)
                                        {
                                            GlGroup glgroup = new GlGroup() { Name = param.Group };
                                            foreach (var e in group.Elements("enum"))
                                            {
                                                GLEnum glEnum = new GLEnum();
                                                var enumName = e.Attribute("name").Value;
                                                glEnum.Initialize(file, enumName);
                                                glgroup.Enums.Add(glEnum);
                                            }
                                            version.Groups.Add(glgroup);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Remove any anums and commands
                    foreach (var remove in feature.Elements("remove"))
                    {
                        foreach (var e in remove.Elements("enum"))
                        {
                            foreach (var group in version.Groups)
                            {
                                var glenum = group.Enums.Find(n => n.Name == e.Attribute("name").Value);

                                if (glenum != null)
                                {
                                    group.Enums.Remove(glenum);
                                }
                            }
                        }

                        foreach (var c in remove.Elements("command"))
                        {
                            version.Commands.RemoveAll(command => command.Name == c.Attribute("name").Value);
                        }
                    }

                    // Remove all group with 0 enums
                    version.Groups.RemoveAll(g => g.Enums.Count == 0);

                    // Remove GLBoolean type
                    version.Groups.RemoveAll(g => g.Name == "Boolean");

                    spec.Versions.Add(version);
                }
            }

            return spec;
        }

19 Source : GLParser.cs
with MIT License
from EvergineTeam

private static string FindGroupInXML(XDoreplacedent file, string enumName)
        {
            string groupFound = string.Empty;
            foreach (var group in file.Root.Element("groups").Elements("group"))
            {
                foreach (var e in group.Elements("enum"))
                {
                    if (enumName == e.Attribute("name").Value)
                    {
                        groupFound = group.Attribute("name").Value;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(groupFound))
                {
                    break;
                }
            }

            if (string.IsNullOrEmpty(groupFound))
            {
                groupFound = "Extensions";
            }

            return groupFound;
        }

19 Source : ExtensionDefinition.cs
with MIT License
from EvergineTeam

public static ExtensionDefinition FromXML(XElement elem)
        {
            ExtensionDefinition extension = new ExtensionDefinition();
            extension.Name = elem.Attribute("name").Value;
            extension.Number = int.Parse(elem.Attribute("number").Value);
            extension.Type = elem.Attribute("type")?.Value;
            extension.Requires = elem.Attribute("requires")?.Value.Split(',');
            extension.Author = elem.Attribute("author")?.Value;
            extension.Contact = elem.Attribute("contact")?.Value;
            extension.Platform = elem.Attribute("platform")?.Value;
            extension.Supported = elem.Attribute("supported")?.Value;
            extension.IsProvisional = elem.Attribute("provisional")?.Value == "true";
            extension.Comment = elem.Attribute("comment")?.Value;
            string sortString = elem.Attribute("sortorder")?.Value;
            if (sortString != null)
            {
                extension.SortOrder = int.Parse(sortString);
            }

            var requires = elem.Element("require");
            if (requires != null)
            {
                var enums = requires.Elements("enum");
                foreach (var e in enums)
                {
                    string enumName = e.Attribute("name").Value;
                    string extends = e.Attribute("extends")?.Value;
                    if (extends != null)
                    {
                        string valueString;
                        string alias = null;
                        string offsetString = e.Attribute("offset")?.Value;
                        if (offsetString != null)
                        {
                            int offset = int.Parse(offsetString);
                            int direction = 1;
                            if (e.Attribute("dir")?.Value == "-")
                            {
                                direction = -1;
                            }

                            string extstring = e.Attribute("extnumber")?.Value;
                            int extNumber = extension.Number;
                            if (extstring != null)
                            {
                                extNumber = int.Parse(extstring);
                            }

                            int value = direction * (1000000000 + (extNumber - 1) * 1000 + offset);
                            valueString = value.ToString();
                        }
                        else
                        {
                            string bitPosString = e.Attribute("bitpos")?.Value;
                            if (bitPosString != null)
                            {
                                int shift = int.Parse(bitPosString);
                                valueString = (1 << shift).ToString();
                            }
                            else
                            {
                                alias = e.Attribute("alias")?.Value;
                                valueString = e.Attribute("value")?.Value;
                            }
                        }

                        extension.Enums.Add(new EnumExtension() { Extends = extends, Name = enumName, Value = valueString, Alias = alias });
                    }
                    else
                    {
                        ConstantExtension constant = new ConstantExtension();
                        constant.Name = enumName;
                        constant.Alias = e.Attribute("alias")?.Value;
                        string rawValue = e.Attribute("value")?.Value;
                        if (rawValue != null)
                            constant.Value = FilterString(rawValue);

                        extension.Constants.Add(constant);
                    }
                }

                var types = requires.Elements("type");
                foreach (var t in types)
                {
                    string name = t.Attribute("name").Value;
                    extension.Types.Add(name);
                }

                var commands = requires.Elements("command");
                foreach (var command in commands)
                {
                    string name = command.Attribute("name").Value;
                    extension.Commands.Add(name);
                }
            }

            return extension;
        }

19 Source : CommandDefinition.cs
with MIT License
from EvergineTeam

public  static CommandDefinition FromXML(XElement elem)
        {
            CommandDefinition command = new CommandDefinition();

            command.SuccessCodes = elem.Attribute("successcodes")?.Value.Split(',');
            command.ErrorCodes = elem.Attribute("errorcodes")?.Value.Split(',');
            command.Queues = elem.Attribute("queues")?.Value.Split(',');
            command.RenderPreplaced = elem.Attribute("renderpreplaced")?.Value;
            command.Pipeline = elem.Attribute("pipeline")?.Value;
            command.CmdBufferLevel = elem.Attribute("cmdbufferlevel")?.Value.Split(',');
            command.Comment = elem.Attribute("comment")?.Value;

            var proto = elem.Element("proto");

            if (proto != null)
            {
                command.Prototype = new Proto
                {
                    Name = proto.Element("name").Value,
                    Type = proto.Element("type").Value,
                };
            }

            var parameters = elem.Elements("param");
            foreach (var param in parameters)
            {
                command.Parameters.Add(Param.FromXML(param));
            }

            return command;
        }

19 Source : EnumDefinition.cs
with MIT License
from EvergineTeam

public static EnumDefinition FromXML(XElement elem)
        {
            EnumDefinition enums = new EnumDefinition();
            enums.Name = elem.Attribute("name").Value;
            enums.Type = elem.Attribute("type").Value == "enum" ? EnumType.Enum : EnumType.Bitmask;
            var values = elem.Elements("enum");
            foreach (var v in values)
            {
                enums.Values.Add(EnumValue.FromXML(v));
            }

            return enums;
        }

19 Source : StructureDefinition.cs
with MIT License
from EvergineTeam

public static StructureDefinition FromXML(XElement elem)
        {
            StructureDefinition s = new StructureDefinition();
            s.Name = elem.Attribute("name").Value;
            s.IsReturnedOnly = elem.Attribute("returnedonly")?.Value == "true";

            var members = elem.Elements("member");
            foreach (var m in members)
            {
                s.Members.Add(Member.FromXML(m));
            }

            return s;
        }

19 Source : VulkanSpecification.cs
with MIT License
from EvergineTeam

public static VulkanSpecification FromFile(string xmlFile)
        {
            XDoreplacedent file = XDoreplacedent.Load(xmlFile);
            VulkanSpecification spec = new VulkanSpecification();

            var registry = file.Element("registry");

            // Platforms
            var platforms = registry.Element("platforms").Elements("platform");
            foreach (var platform in platforms)
            {
                spec.Platforms.Add(PlatformDefinition.FromXML(platform));
            }

            // Tags
            var tags = registry.Element("tags").Elements("tag");
            foreach (var tag in tags)
            {
                spec.Tags.Add(TagDefinition.FromXML(tag));
            }

            // Constants
            var constants = (registry.Elements("enums").Where(e => e.Attribute("name").Value == "API Constants")).Elements("enum");
            foreach (var c in constants)
            {
                spec.Constants.Add(ConstantDefinition.FromXML(c));
            }

            // Enums
            var enums = registry.Elements("enums").Where(e => e.Attribute("type")?.Value == "enum" || e.Attribute("type")?.Value == "bitmask");
            foreach (var e in enums)
            {
                spec.Enums.Add(EnumDefinition.FromXML(e));
            }

            var types = registry.Elements("types");

            // FuncPointers
            var funcPointers = types.Elements("type").Where(f => f.Attribute("category")?.Value == "funcpointer");
            foreach (var func in funcPointers)
            {
                spec.FuncPointers.Add(FuncpointerDefinition.FromXML(func));
            }

            // Alias
            spec.Alias = types.Elements("type").Where(a => a.Attribute("alias") != null)
                .ToDictionary(
                    a => a.Attribute("name").Value,
                    a => a.Attribute("alias").Value);

            // Command Alias
            var commandAlias = registry.Element("commands").Elements("command").Where(c => c.Attribute("alias") != null);
            foreach (var c in commandAlias)
            {
                spec.Alias.Add(c.Attribute("name").Value, c.Attribute("alias").Value);
            }

            // Structs
            var structs = types.Elements("type").Where(s => s.Attribute("category")?.Value == "struct" && s.Attribute("alias") == null);
            foreach (var s in structs)
            {
                spec.Structs.Add(StructureDefinition.FromXML(s));
            }

            // Unions
            var unions = types.Elements("type").Where(u => u.Attribute("category")?.Value == "union");
            foreach (var u in unions)
            {
                spec.Unions.Add(StructureDefinition.FromXML(u));
            }

            // TypeDef
            var typeDefs = types.Elements("type").Where(t => t.Value.Contains("typedef") &&  t.Attribute("category")?.Value == "bitmask");
            foreach (var type in typeDefs)
            {
                spec.TypeDefs.Add(TypedefDefinition.FromXML(type));
            }

            // BaseTypes
            spec.BaseTypes = types.Elements("type").Where(bt => bt.Attribute("category")?.Value == "basetype")
                .ToDictionary(
                    bt => bt.Element("name").Value,
                    bt => bt.Element("type")?.Value);

            // Handles
            var handles = types.Elements("type").Where(h => h.Attribute("category")?.Value == "handle");
            foreach (var h in handles)
            {
                spec.Handles.Add(HandleDefinition.FromXML(h));
            }

            // Commands
            var commands = registry.Element("commands").Elements("command").Where(c => c.Attribute("alias") == null);
            foreach (var command in commands)
            {
                spec.Commands.Add(CommandDefinition.FromXML(command));
            }

            // Features
            var features = registry.Elements("feature");
            foreach (var feature in features)
            {
                spec.Features.Add(FeatureDefinition.FromXML(feature));
            
            }

            // Extensions
            var extensions = registry.Element("extensions").Elements("extension");
            foreach (var extension in extensions)
            {
                spec.Extensions.Add(ExtensionDefinition.FromXML(extension));
            }

            return spec;
        }

19 Source : GLParser.cs
with MIT License
from EvergineTeam

internal void Initialize(XDoreplacedent file, string enumName)
            {
                this.Name = enumName;
                this.ShortName = ComputeShortName(enumName);

                foreach (var enumsElements in file.Root.Elements("enums"))
                {
                    foreach (var enumElem in enumsElements.Elements("enum"))
                    {
                        if (enumElem.Attribute("name").Value == enumName &&
                            (enumElem.Attribute("api") == null)) // || enumElem.Attribute("api").Value == api))
                        {
                            this.Value = enumElem.Attribute("value").Value;
                            break;
                        }
                    }

                    if (!string.IsNullOrEmpty(this.Value))
                    {
                        break;
                    }
                }
            }

19 Source : GLParser.cs
with MIT License
from EvergineTeam

public void Initialize(XDoreplacedent specDoc)
            {
                var commandElem = (from elem in specDoc.Root.Element("commands").Elements("command")
                                   where elem.Element("proto").Element("name").Value == Name
                                   select elem).First();

                var proto = commandElem.Element("proto");
                ReturnType = new GLReturnType();
                ReturnType.Type = proto.Value.Replace(Name, string.Empty).Trim();
                ReturnType.Group = proto.Attribute("group")?.Value;

                foreach (var p in commandElem.Elements("param"))
                {
                    var param = new GLParameter { Name = p.Element("name").Value };
                    param.Type = p.Value.Substring(0, p.Value.LastIndexOf(param.Name)).Trim();
                    if (p.Attribute("group") != null)
                    {
                        param.Group = p.Attribute("group").Value;
                    }
                    Parameters.Add(param);
                }
            }

19 Source : FeatureDefinition.cs
with MIT License
from EvergineTeam

public static FeatureDefinition FromXML(XElement elem)
        {
            FeatureDefinition feature = new FeatureDefinition();
            feature.Name = elem.Attribute("name").Value;
            feature.Number = elem.Attribute("number").Value;
            feature.Api = elem.Attribute("api").Value;
            feature.Comment = elem.Attribute("comment")?.Value;

            var requires = elem.Elements("require");
            foreach (var require in requires)
            {
                var enums = require.Elements("enum");
                foreach (var e in enums)
                {
                    string enumName = e.Attribute("name").Value;
                    string extends = e.Attribute("extends")?.Value;
                    if (extends != null)
                    {
                        string valueString;
                        string alias = null;
                        string offsetString = e.Attribute("offset")?.Value;
                        if (offsetString != null)
                        {
                            int extNumber = int.Parse(e.Attribute("extnumber").Value);
                            int offset = int.Parse(offsetString);
                            int direction = 1;
                            if (e.Attribute("dir")?.Value == "-")
                            {
                                direction = -1;
                            }

                            int value = direction * (1000000000 + (extNumber - 1) * 1000 + offset);
                            valueString = value.ToString();
                        }
                        else
                        {
                            string bitPosString = e.Attribute("bitpos")?.Value;
                            if (bitPosString != null)
                            {
                                int shift = int.Parse(bitPosString);
                                valueString = (1 << shift).ToString();
                            }
                            else
                            {
                                alias = e.Attribute("alias")?.Value;
                                valueString = e.Attribute("value")?.Value;
                            }
                        }

                        feature.Enums.Add(new EnumFeature() { Extends = extends, Name = enumName, Value = valueString, Alias = alias });
                    }
                    else
                    {
                        ConstantFeature constant = new ConstantFeature();
                        constant.Name = enumName;
                        constant.Alias = e.Attribute("alias")?.Value;
                        constant.Value = e.Attribute("value")?.Value;

                        feature.Constants.Add(constant);
                    }
                }

                var types = require.Elements("type");
                foreach (var t in types)
                {
                    string name = t.Attribute("name").Value;
                    feature.Types.Add(name);
                }

                var commands = require.Elements("command");
                foreach (var command in commands)
                {
                    string name = command.Attribute("name").Value;
                    feature.Commands.Add(name);
                }
            }

            return feature;
        }

19 Source : DCSSchemaDocument.cs
with Apache License 2.0
from EvilBeaver

private void JoinSchemaAndVariants(string tmp_SchemaContent, List<string> settingsList)
        {
            XNamespace schemaNS = XNamespace.Get("http://v8.1c.ru/8.1/data-composition-system/schema");
            XNamespace settingsNS = XNamespace.Get("http://v8.1c.ru/8.1/data-composition-system/settings");

            Utils.XMLMerge.NamespaceMap nsMap = new Utils.XMLMerge.NamespaceMap();
            nsMap.Add("dcsset", settingsNS.NamespaceName);
            nsMap.Add("dcscor", "http://v8.1c.ru/8.1/data-composition-system/core");
            nsMap.Add("xs"    , "http://www.w3.org/2001/XMLSchema");
            nsMap.Add("xsi"   , "http://www.w3.org/2001/XMLSchema-instance");

            XDoreplacedent File = XDoreplacedent.Parse(tmp_SchemaContent);
            XContainer schema = File.Root.Element(XName.Get("dataCompositionSchema", schemaNS.NamespaceName));

            if (schema == null)
            {
                _SchemaContent = tmp_SchemaContent;
                return;
            }

            if (settingsList.Count == 0)
            {
                _SchemaContent = schema.ToString();
                return;
            }

            var elemVariants = schema.Elements(XName.Get("settingsVariant", schemaNS.NamespaceName));
            if (elemVariants == null)
            {
                // непонятная ситуация, в схеме нет описания вариантов, но сами варианты есть.
                // пока оставим просто схему, потом видно будет
                _SchemaContent = schema.ToString();
                return;
            }

            int i = 0;
            foreach (var variant in elemVariants)
            {
                if (i >= settingsList.Count)
                {
                    break;
                }

                var settings = XDoreplacedent.Parse(settingsList[i++]);
                
                if (settings.Root.GetDefaultNamespace() == settingsNS)
                {
                    XName currentName = XName.Get("settings",settingsNS.NamespaceName);
                    settings.Root.Name = currentName;

                    Utils.XMLMerge.Perform(variant, settings.Root, nsMap);
                    
                    //variant.Add(settings.Root);
                }

            }

            _SchemaContent = schema.ToString();
        }

19 Source : UpdateChecker.cs
with Apache License 2.0
from EvilBeaver

UpdateLog LoadResult(WebResponse response)
        {
            XDoreplacedent xmlDoc;

            using (var stream = response.GetResponseStream())
            {
                try
                {
                    xmlDoc = XDoreplacedent.Load(stream);
                }
                catch (Exception exc)
                {
                    throw new UpdaterException("Некорректные данные об обновлении", exc);
                }
            }

            var VersionList = xmlDoc.Root.Elements("version");
            var currentVer = System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Version;
            UpdateLog log = new UpdateLog();

            foreach (var vDeclaration in VersionList)
            {
                Version inFile = Version.Parse(vDeclaration.Attribute("number").Value);
                if (currentVer < inFile)
                {
                    UpdateDefinition upd = new UpdateDefinition();
                    upd.Version = inFile.ToString();
                    upd.Url = vDeclaration.Element("url").Value;
                    upd.News = vDeclaration.Element("news").Value;
                    log.Add(upd);
                }
            }

            return log;
        }

See More Examples