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

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

1283 Examples 7

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

internal static int? GetFormalCharge(XElement cmlElement)
        {
            int formalCharge;

            if (int.TryParse(cmlElement.Attribute(CMLConstants.AttributeFormalCharge)?.Value, out formalCharge))
            {
                return formalCharge;
            }
            else
            {
                return null;
            }
        }

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

internal static Point GetPosn(XElement cmlElement, out string message)
        {
            message = "";
            string symbol = cmlElement.Attribute(CMLConstants.AttributeElementType)?.Value;
            string id = cmlElement.Attribute(CMLConstants.AttributeId)?.Value;

            Point result = new Point();
            bool found = false;

            // Try first with 2D Co-ordinate scheme
            if (cmlElement.Attribute(CMLConstants.AttributeX2) != null && cmlElement.Attribute(CMLConstants.AttributeY2) != null)
            {
                result = new Point(
                    Double.Parse(cmlElement.Attribute(CMLConstants.AttributeX2).Value, CultureInfo.InvariantCulture),
                    Double.Parse(cmlElement.Attribute(CMLConstants.AttributeY2).Value, CultureInfo.InvariantCulture));
                found = true;
            }

            if (!found)
            {
                // Try again with 3D Co-ordinate scheme
                if (cmlElement.Attribute(CMLConstants.AttributeX3) != null && cmlElement.Attribute(CMLConstants.AttributeY3) != null)
                {
                    result = new Point(
                        Double.Parse(cmlElement.Attribute(CMLConstants.AttributeX3).Value, CultureInfo.InvariantCulture),
                        Double.Parse(cmlElement.Attribute(CMLConstants.AttributeY3).Value, CultureInfo.InvariantCulture));
                    found = true;
                }
            }

            if (!found)
            {
                message = $"No atom co-ordinates found for atom '{symbol}' with id of '{id}'.";
            }
            return result;
        }

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

public static bool? GetExplicit(XElement cmlElement)
        {
            bool expl;

            if (bool.TryParse(cmlElement.Attribute(CMLNamespaces.c4w + CMLConstants.AttributeExplicit)?.Value, out expl))
            {
                return expl;
            }
            else
            {
                return null;
            }
        }

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

private static Atom GetAtom(XElement cmlElement)
        {
            Atom atom = new Atom();

            atom.Messages = new List<string>();
            string message = "";
            string atomLabel = cmlElement.Attribute(CMLConstants.AttributeId)?.Value;

            Point p = CMLHelper.GetPosn(cmlElement, out message);
            if (!string.IsNullOrEmpty(message))
            {
                atom.Messages.Add(message);
            }

            atom.Id = atomLabel;
            atom.Position = p;

            ElementBase e = CMLHelper.GetElementOrFunctionalGroup(cmlElement, out message);
            if (!string.IsNullOrEmpty(message))
            {
                atom.Messages.Add(message);
            }

            if (e != null)
            {
                atom.Element = e;
                atom.FormalCharge = CMLHelper.GetFormalCharge(cmlElement);
                atom.IsotopeNumber = CMLHelper.GetIsotopeNumber(cmlElement);
                atom.ExplicitC = CMLHelper.GetExplicit(cmlElement);
            }

            return atom;
        }

19 Source : FixRedirectsCommandPackage.cs
with MIT License
from CloudNimble

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }

19 Source : NuGetUpgraderPackage.cs
with MIT License
from CloudNimble

private void UpgradePackagesConfig()
        {

            _isProcessing = true;

            var files = ProjectHelpers.GetSelectedItems().Where(c => _fileNames.Contains(Path.GetFileName(c.GetFullPath())));

            if (!files.Any())
            {
                _dte.StatusBar.Text = "Please select a package.config file to nuke from orbit.";
                _isProcessing = false;
                return;
            }

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

            //RWM: Don't mess with these.
            XNamespace defaultNs = "http://schemas.microsoft.com/developer/msbuild/2003";
            var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };

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

                Parallel.For(0, count, options, i =>
                {
                    var packageReferences = new XElement(defaultNs + "ItemGroup");
                    var packagesConfigItem = files.ElementAt(i);
                    var packagesConfigPath = packagesConfigItem.GetFullPath();
                    var projectPath = packagesConfigItem.ContainingProject.FileName;

                    //RWM: Start by backing up the files.
                    File.Copy(packagesConfigPath, $"{packagesConfigPath}.bak", true);
                    File.Copy(projectPath, $"{projectPath}.bak", true);

                    Logger.Log($"Backup created for {packagesConfigPath}.");

                    //RWM: Load the files.
                    var project = XDoreplacedent.Load(projectPath);
                    var packagesConfig = XDoreplacedent.Load(packagesConfigPath);

                    //RWM: Get references to the stuff we're gonna get rid of.
                    var oldReferences = project.Root.Descendants().Where(c => c.Name.LocalName == "Reference");
                    var errors = project.Root.Descendants().Where(c => c.Name.LocalName == "Error");
                    var targets = project.Root.Descendants().Where(c => c.Name.LocalName == "Import");

                    foreach (var row in packagesConfig.Root.Elements().ToList())
                    {
                        //RWM: Create the new PackageReference.
                        packageReferences.Add(new XElement(defaultNs + "PackageReference",
                            new XAttribute("Include", row.Attribute("id").Value),
                            new XAttribute("Version", row.Attribute("version").Value)));

                        //RWM: Remove the old Standard Reference.
                        oldReferences.Where(c => c.Attribute("Include").Value.Split(new Char[] { ',' })[0].ToLower() == row.Attribute("id").Value.ToLower()).ToList()
                            .ForEach(c => c.Remove());
                        //RWM: Remove any remaining Standard References where the PackageId is in the HintPath.
                        oldReferences.Where(c => c.Descendants().Any(d => d.Value.Contains(row.Attribute("id").Value))).ToList()
                            .ForEach(c => c.Remove());
                        //RWM: Remove any Error conditions for missing Package Targets.
                        errors.Where(c => c.Attribute("Condition").Value.Contains(row.Attribute("id").Value)).ToList()
                            .ForEach(c => c.Remove());
                        //RWM: Remove any Package Targets.
                        targets.Where(c => c.Attribute("Project").Value.Contains(row.Attribute("id").Value)).ToList()
                            .ForEach(c => c.Remove());
                    }

                    //RWM: Fix up the project file by adding PackageReferences, removing packages.config, and pulling NuGet-added Targets.
                    project.Root.Elements().First(c => c.Name.LocalName == "ItemGroup").AddBeforeSelf(packageReferences);
                    var packageConfigReference = project.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "None" && c.Attribute("Include").Value == "packages.config");
                    if (packageConfigReference != null)
                    {
                        packageConfigReference.Remove();
                    }

                    var nugetBuildImports = project.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "Target" && c.Attribute("Name").Value == "EnsureNuGetPackageBuildImports");
                    if (nugetBuildImports != null && nugetBuildImports.Descendants().Count(c => c.Name.LocalName == "Error") == 0)
                    {
                        nugetBuildImports.Remove();
                    }

                    //RWM: Upgrade the ToolsVersion so it can't be opened in VS2015 anymore.
                    project.Root.Attribute("ToolsVersion").Value = "15.0";

                    //RWM: Save the project and delete Packages.config.
                    ProjectHelpers.CheckFileOutOfSourceControl(projectPath);
                    ProjectHelpers.CheckFileOutOfSourceControl(packagesConfigPath);
                    project.Save(projectPath, SaveOptions.None);
                    File.Delete(packagesConfigPath);

                    Logger.Log($"Update complete. Visual Studio will prompt you to reload the project now.");
                });
            }
            catch (AggregateException agEx)
            {
                _dte.StatusBar.Progress(false);
                Logger.Log($"Update failed. Exceptions:");
                foreach (var ex in agEx.InnerExceptions)
                {
                    Logger.Log($"Message: {ex.Message}{Environment.NewLine}{ex.StackTrace}");
                }
                _dte.StatusBar.Text = "Operation failed. Please see Output Window for details.";
                _isProcessing = false;

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

        }

19 Source : SystemMenuManage.cs
with Apache License 2.0
from Coldairarrow

private static void InitAllMenu()
        {
            Action<Menu, XElement> SetMenuProperty = (menu, element) =>
            {
                List<string> exceptProperties = new List<string> { "Id", "IsShow" };
                menu.GetType().GetProperties().Where(x => !exceptProperties.Contains(x.Name)).ForEach(aProperty =>
                {
                    aProperty.SetValue(menu, element.Attribute(aProperty.Name)?.Value);
                });
            };

            string filePath = _configFile;
            XElement xe = XElement.Load(filePath);
            List<Menu> menus = new List<Menu>();
            xe.Elements("FirstMenu")?.ForEach(aElement1 =>
            {
                Menu newMenu1 = new Menu();
                menus.Add(newMenu1);
                SetMenuProperty(newMenu1, aElement1);
                newMenu1.SubMenus = new List<Menu>();
                aElement1.Elements("SecondMenu")?.ForEach(aElement2 =>
                {
                    Menu newMenu2 = new Menu();
                    newMenu1.SubMenus.Add(newMenu2);
                    SetMenuProperty(newMenu2, aElement2);
                    newMenu2.SubMenus = new List<Menu>();

                    aElement2.Elements("ThirdMenu")?.ForEach(aElement3 =>
                    {
                        Menu newMenu3 = new Menu();
                        newMenu2.SubMenus.Add(newMenu3);
                        SetMenuProperty(newMenu3, aElement3);
                        if (!newMenu3.Url.IsNullOrEmpty())
                        {
                            UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetService<IActionContextAccessor>().ActionContext);
                            newMenu3.Url = urlHelper.Content(newMenu3.Url);
                        }
                    });
                });
            });

            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                Menu newMenu1 = new Menu
                {
                    Name = "开发",
                    Icon = "icon_menu_prod",
                    SubMenus = new List<Menu>()
                };
                menus.Add(newMenu1);
                Menu newMenu1_1 = new Menu
                {
                    Name = "快速开发",
                    SubMenus = new List<Menu>()
                };
                newMenu1.SubMenus.Add(newMenu1_1);
                Menu newMenu1_1_1 = new Menu
                {
                    Name = "代码生成",
                    Url = GetUrl("~/Base_SysManage/RapidDevelopment/Index")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_1);

                Menu newMenu1_1_2 = new Menu
                {
                    Name = "数据库连接管理",
                    Url = GetUrl("~/Base_SysManage/Base_DatabaseLink/Index")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_2);

                Menu newMenu1_1_3 = new Menu
                {
                    Name = "UEditor Demo",
                    Url = GetUrl("~/Demo/UMEditor")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_3);

                Menu newMenu1_1_4 = new Menu
                {
                    Name = "文件上传Demo",
                    Url = GetUrl("~/Demo/UploadFileIndex")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_4);
            }

            _allMenu = menus;
        }

19 Source : SystemMenuManage.cs
with Apache License 2.0
from Coldairarrow

private static void InitAllMenu()
        {
            Action<Menu, XElement> SetMenuProperty = (menu, element) =>
            {
                List<string> exceptProperties = new List<string> { "Id", "IsShow" };
                menu.GetType().GetProperties().Where(x => !exceptProperties.Contains(x.Name)).ForEach(aProperty =>
                {
                    aProperty.SetValue(menu, element.Attribute(aProperty.Name)?.Value);
                });
            };

            string filePath = HttpContext.Current.Server.MapPath(_configFile);
            XElement xe = XElement.Load(filePath);
            List<Menu> menus = new List<Menu>();
            xe.Elements("FirstMenu")?.ForEach(aElement1 =>
            {
                Menu newMenu1 = new Menu();
                menus.Add(newMenu1);
                SetMenuProperty(newMenu1, aElement1);
                newMenu1.SubMenus = new List<Menu>();
                aElement1.Elements("SecondMenu")?.ForEach(aElement2 =>
                {
                    Menu newMenu2 = new Menu();
                    newMenu1.SubMenus.Add(newMenu2);
                    SetMenuProperty(newMenu2, aElement2);
                    newMenu2.SubMenus = new List<Menu>();

                    aElement2.Elements("ThirdMenu")?.ForEach(aElement3 =>
                    {
                        Menu newMenu3 = new Menu();
                        newMenu2.SubMenus.Add(newMenu3);
                        SetMenuProperty(newMenu3, aElement3);
                        if (!newMenu3.Url.IsNullOrEmpty())
                        {
                            newMenu3.Url = GetUrl(newMenu3.Url);
                        }
                    });
                });
            });

            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                Menu newMenu1 = new Menu
                {
                    Name = "开发",
                    Icon = "icon_menu_prod",
                    SubMenus = new List<Menu>()
                };
                menus.Add(newMenu1);
                Menu newMenu1_1 = new Menu
                {
                    Name = "快速开发",
                    SubMenus = new List<Menu>()
                };
                newMenu1.SubMenus.Add(newMenu1_1);
                Menu newMenu1_1_1 = new Menu
                {
                    Name = "代码生成",
                    Url = GetUrl("~/Base_SysManage/RapidDevelopment/Index")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_1);

                Menu newMenu1_1_2 = new Menu
                {
                    Name = "数据库连接管理",
                    Url = GetUrl("~/Base_SysManage/Base_DatabaseLink/Index")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_2);

                Menu newMenu1_1_3 = new Menu
                {
                    Name = "UEditor Demo",
                    Url = GetUrl("~/Demo/UMEditor")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_3);

                Menu newMenu1_1_4 = new Menu
                {
                    Name = "文件上传Demo",
                    Url = GetUrl("~/Demo/UploadFileIndex")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_4);
            }

            _allMenu = menus;
        }

19 Source : SystemMenuManage.cs
with MIT License
from Coldairarrow

private static void InitAllMenu()
        {
            Action<Menu, XElement> SetMenuProperty = (menu, element) =>
            {
                List<string> exceptProperties = new List<string> { "id", "IsShow", "targetType", "isHeader", "children", "_url" };
                menu.GetType().GetProperties().Where(x => !exceptProperties.Contains(x.Name)).ForEach(aProperty =>
                {
                    aProperty.SetValue(menu, element.Attribute(aProperty.Name)?.Value);
                });
            };

            string filePath = _configFile;
            XElement xe = XElement.Load(filePath);
            List<Menu> menus = new List<Menu>();
            xe.Elements("FirstMenu")?.ForEach(aElement1 =>
            {
                Menu newMenu1 = new Menu();
                menus.Add(newMenu1);
                SetMenuProperty(newMenu1, aElement1);
                newMenu1.children = new List<Menu>();
                aElement1.Elements("SecondMenu")?.ForEach(aElement2 =>
                {
                    Menu newMenu2 = new Menu();
                    newMenu1.children.Add(newMenu2);
                    SetMenuProperty(newMenu2, aElement2);
                    newMenu2.children = new List<Menu>();

                    aElement2.Elements("ThirdMenu")?.ForEach(aElement3 =>
                    {
                        Menu newMenu3 = new Menu();
                        newMenu2.children.Add(newMenu3);
                        SetMenuProperty(newMenu3, aElement3);
                        if (!newMenu3.url.IsNullOrEmpty())
                        {
                            newMenu3.url = GetUrl(newMenu3.url);
                        }
                    });
                });
            });

            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                Menu developMenu = new Menu
                {
                    text = "开发",
                    icon = "glyphicon glyphicon-console",
                    children = new List<Menu>()
                };
                menus.Add(developMenu);
                developMenu.children.Add(new Menu
                {
                    text = "代码生成",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Base_SysManage/RapidDevelopment/Index")
                });
                developMenu.children.Add(new Menu
                {
                    text = "数据库连接管理",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Base_SysManage/Base_DatabaseLink/Index")
                });
                developMenu.children.Add(new Menu
                {
                    text = "UMEditor Demo",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/UMEditor")
                });
                developMenu.children.Add(new Menu
                {
                    text = "下拉搜索",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/SelectSearch")
                });
                developMenu.children.Add(new Menu
                {
                    text = "上传文件",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/UploadFile")
                });
                developMenu.children.Add(new Menu
                {
                    text = "下载文件",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/DownloadFile")
                });
                developMenu.children.Add(new Menu
                {
                    text = "表格树及下拉树",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Base_SysManage/Base_Department/Index")
                });
                developMenu.children.Add(new Menu
                {
                    text = "API签名Demo",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/ApiSignDemo")
                });
                developMenu.children.Add(new Menu
                {
                    text = "Tab页",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/Tab")
                });
                developMenu.children.Add(new Menu
                {
                    text = "详情页",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/Details")
                });
            }

            _allMenu = menus;
        }

19 Source : SystemMenuManage.cs
with MIT License
from Coldairarrow

private static void InitAllMenu()
        {
            Action<Menu, XElement> SetMenuProperty = (menu, element) =>
            {
                List<string> exceptProperties = new List<string> { "id", "IsShow", "targetType", "isHeader", "children", "_url" };
                menu.GetType().GetProperties().Where(x => !exceptProperties.Contains(x.Name)).ForEach(aProperty =>
                {
                    aProperty.SetValue(menu, element.Attribute(aProperty.Name)?.Value);
                });
            };

            string filePath = _configFile;
            XElement xe = XElement.Load(filePath);
            List<Menu> menus = new List<Menu>();
            xe.Elements("FirstMenu")?.ForEach(aElement1 =>
            {
                Menu newMenu1 = new Menu();
                menus.Add(newMenu1);
                SetMenuProperty(newMenu1, aElement1);
                newMenu1.children = new List<Menu>();
                aElement1.Elements("SecondMenu")?.ForEach(aElement2 =>
                {
                    Menu newMenu2 = new Menu();
                    newMenu1.children.Add(newMenu2);
                    SetMenuProperty(newMenu2, aElement2);
                    newMenu2.children = new List<Menu>();

                    aElement2.Elements("ThirdMenu")?.ForEach(aElement3 =>
                    {
                        Menu newMenu3 = new Menu();
                        newMenu2.children.Add(newMenu3);
                        SetMenuProperty(newMenu3, aElement3);
                        if (!newMenu3.url.IsNullOrEmpty())
                        {
                            newMenu3.url = GetUrl(newMenu3.url);
                        }
                    });
                });
            });

            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                Menu developMenu = new Menu
                {
                    text = "开发",
                    icon = "glyphicon glyphicon-console",
                    children = new List<Menu>()
                };
                menus.Add(developMenu);
                developMenu.children.Add(new Menu
                {
                    text = "代码生成",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Base_SysManage/RapidDevelopment/Index")
                });
                developMenu.children.Add(new Menu
                {
                    text = "数据库连接管理",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Base_SysManage/Base_DatabaseLink/Index")
                });
                developMenu.children.Add(new Menu
                {
                    text = "UMEditor Demo",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/UMEditor")
                });
                developMenu.children.Add(new Menu
                {
                    text = "下拉搜索",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/SelectSearch")
                });
                developMenu.children.Add(new Menu
                {
                    text = "上传文件",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/UploadFile")
                });
                developMenu.children.Add(new Menu
                {
                    text = "下载文件",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/DownloadFile")
                });
                developMenu.children.Add(new Menu
                {
                    text = "表格树及下拉树",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Base_SysManage/Base_Department/Index")
                });
                developMenu.children.Add(new Menu
                {
                    text = "API签名Demo",
                    icon = "fa fa-circle-o",
                    url = GetUrl("~/Demo/ApiSignDemo")
                });
            }

            _allMenu = menus;
        }

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

private static dynamic ToValue(XElement element)
        {
            var type = (JsonType)Enum.Parse(typeof(JsonType), element.Attribute("type").Value);
            switch (type)
            {
                case JsonType.boolean:
                    return (bool)element;
                case JsonType.number:
                    return (double)element;
                case JsonType.@string:
                    return (string)element;
                case JsonType.@object:
                case JsonType.array:
                    return new DynamicJson(element, type);
                case JsonType.@null:
                default:
                    return null;
            }
        }

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

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

            return true;
        }

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

private bool TrySet(int index, object value)
        {
            var type = GetJsonType(value);
            var e = xml.Elements().ElementAtOrDefault(index);
            if (e == null)
            {
                xml.Add(new XElement("item", CreateTypeAttr(type), CreateJsonNode(value)));
            }
            else
            {
                e.Attribute("type").Value = type.ToString();
                e.ReplaceNodes(CreateJsonNode(value));
            }

            return true;
        }

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

public override string ToString()
        {
            // <foo type="null"></foo> is can't serialize. replace to <foo type="null" />
            foreach (var elem in xml.Descendants().Where(x => x.Attribute("type").Value == "null"))
            {
                elem.RemoveNodes();
            }
            return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(jsonType), xml.Elements()));
        }

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

public bool HasAttribute(string name)
        {
            return (_element != null && _element.Attribute(name) != null);
        }

19 Source : NUnitEventListener.cs
with MIT License
from ComparetheMarket

private void HandleTestStarting(string report)
        {
            var doc = XDoreplacedent.Parse(report);

            var testName = doc.Root.Attribute("fullname").Value;

            onTestStarting(testName);
        }

19 Source : NUnitEventListener.cs
with MIT License
from ComparetheMarket

private void HandleTestComplete(string report)
        {
            var doc = XDoreplacedent.Parse(report);

            var testName = doc.Root.Attribute("fullname").Value;

            var isParameterized = testName.EndsWith(")");
            if (isParameterized)
            {
                testName = WithoutParameters(testName);
            }

            testCasesWithinFixture.Add(testName);

            var calledMemberIds = ParseExecutedMemberIdsFromOutput(doc);

            onTestComplete(testName, calledMemberIds);
        }

19 Source : Program.cs
with MIT License
from CXuesong

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            Random rand = new Random();

            var selectedEnreplacedies = new LinkedList<ScaledEnreplacedy>();

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

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

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

            return selectedEnreplacedies;
        }

19 Source : XmlExtensions.cs
with Apache License 2.0
from danielpalme

public static IEnumerable<TasklistViewModel> FromXml(this XDoreplacedent tasklists)
        {
            return tasklists.Root.Elements("Task").Select(t => new TasklistViewModel(
                 t.Elements("TaskItem").Select(st => new SyncTaskViewModel(
                    new Synchronization.SyncTask(st.Attribute("Name").Value)
                    {
                        IsActive = (bool)st.Attribute("Active"),
                        ReferenceDirectory = st.Attribute("ReferenceDirectory").Value,
                        TargetDirectory = st.Attribute("TargetDirectory").Value,
                        Recursive = (bool)st.Attribute("Recursive"),
                        Filter = st.Attribute("Filter").Value,
                        LastSyncDate = ((DateTime)st.Attribute("LastSynced")).Equals(new DateTime()) ? (DateTime?)null : (DateTime)st.Attribute("LastSynced")
                    })
                    {
                        SyncModeType = (SyncModeType)Enum.Parse(typeof(SyncModeType), st.Attribute("SyncMode").Value)
                    }),
                t.Attribute("Name").Value)
            {
                LastSyncDate = ((DateTime)t.Attribute("LastSynced")).Equals(new DateTime()) ? (DateTime?)null : (DateTime)t.Attribute("LastSynced")
            });
        }

19 Source : ConfigurationManagerImplementation.cs
with MIT License
from dansiegel

private static ConnectionStringSettings GenerateConnectionStringSettingsFromItem(XElement xElement) => new ConnectionStringSettings(xElement.Attribute(AppConfigElement.Name)?.Value,
            xElement.Attribute(AppConfigElement.ProviderName)?.Value,
            xElement.Attribute(AppConfigElement.ConnectionString)?.Value);

19 Source : ConfigurationManagerImplementation.cs
with MIT License
from dansiegel

private static KeyValuePair<string, string> GenerateKeyValueFromItem(XElement item) => new KeyValuePair<string, string>(
            item?.Attribute(AppConfigElement.Key)?.Value,
            item?.Attribute(AppConfigElement.Value)?.Value);

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

void RemoveAndroidPermissions(IEnumerable<string> permissions)
        {
            var perms = new HashSet<string>(permissions);
            var list = manifest.Elements("uses-permission")
                .Where(el => perms.Contains((string)el.Attribute(aName))).ToList();
            foreach (var el in list)
                el.Remove();
        }

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

[Obsolete("This should not be needed anymore; Activity execution is not part of installation.")]
        public string GetLaunchableFastDevActivityName()
        {
            string first = null;
            foreach (var a in GetLaunchableActivities())
            {
                var name = (string)a.Attribute(aName);
                //prefer the fastdev launcher, it's quicker
                if (name == "mono.android.__FastDevLauncher")
                {
                    return name;
                }
                //else just use the first other launchable activity
                if (first == null)
                {
                    first = name;
                }
            }

            return string.IsNullOrEmpty(first) ? null : first;
        }

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

public string GetLaunchableUserActivityName()
        {
            return GetLaunchableActivities()
                .Select(a => (string)a.Attribute(aName))
                .FirstOrDefault(name => !string.IsNullOrEmpty(name) && name != "mono.android.__FastDevLauncher");
        }

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

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

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

public IEnumerable<string> GetAllActivityNames()
        {
            foreach (var activity in application.Elements("activity"))
            {
                var activityName = (string)activity.Attribute(aName);
                if (activityName != "mono.android.__FastDevLauncher")
                    yield return activityName;
            }
        }

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

public IEnumerable<string> GetLaunchableActivityNames()
        {
            return GetLaunchableActivities()
                .Select(a => (string)a.Attribute(aName))
                .Where(name => !string.IsNullOrEmpty(name) && name != "mono.android.__FastDevLauncher");
        }

19 Source : BindableDynamicObject.cs
with Apache License 2.0
from DataBooster

internal void ReadXml(XElement xe)
			{
				XNamespace defaultNamespace = xe.GetDefaultNamespace();
				bool? serializePropertyAsAttribute = (bool?)xe.Attribute(defaultNamespace + "SerializePropertyAsAttribute");
				bool? emitNullValue = (bool?)xe.Attribute(defaultNamespace + "EmitNullValue");
				string typeSchema = (string)xe.Attribute(defaultNamespace + "TypeSchema");

				if (serializePropertyAsAttribute.HasValue)
					_SerializePropertyAsAttribute = serializePropertyAsAttribute.Value;

				if (emitNullValue.HasValue)
					_EmitNullValue = emitNullValue.Value;

				if (!string.IsNullOrWhiteSpace(typeSchema))
					_TypeSchema = (DataTypeSchema)Enum.Parse(typeof(DataTypeSchema), typeSchema, true);
			}

19 Source : XmlWriterExtensions.cs
with Apache License 2.0
from DataBooster

private static string GetXsdTypeAttributeString(this XElement xe)
		{
			XAttribute declaredAttribute = xe.Attribute(XNsXsi + XsdTypeAttributeName);

			if (declaredAttribute == null)
				return null;
			if (string.IsNullOrEmpty(declaredAttribute.Value))
				return declaredAttribute.Value;

			string declaredType = declaredAttribute.Value;
			int colon = declaredType.IndexOf(':');

			return (colon < 0) ? declaredType : declaredType.Substring(colon + 1);
		}

19 Source : XmlWriterExtensions.cs
with Apache License 2.0
from DataBooster

internal static object ReadValue(this XElement xe, BindableDynamicObject.XmlSettings xmlSettings)
		{
			if ((bool?)xe.Attribute(XnNil) ?? false)
				return null;

			string declaredType = null;

			switch (xmlSettings.TypeSchema)
			{
				case BindableDynamicObject.XmlSettings.DataTypeSchema.Xsd:
					declaredType = xe.GetXsdTypeAttributeString();
					if (string.IsNullOrEmpty(declaredType))
					{
						if (xmlSettings.IsImplicit())
							declaredType = xe.GetNetTypeAttributeString();
					}
					else
					{
						try { return _XsdDataContractSerializer.ReadObject(xe.CreateReader(), false); }
						catch { }
					}
					break;

				case BindableDynamicObject.XmlSettings.DataTypeSchema.Net:
					declaredType = xe.GetNetTypeAttributeString();
					if (declaredType == null && xmlSettings.IsImplicit())
						declaredType = xe.GetXsdTypeAttributeString();
					break;

				default:
					if (xmlSettings.IsImplicit())
					{
						declaredType = xe.GetXsdTypeAttributeString();
						if (string.IsNullOrEmpty(declaredType))
							declaredType = xe.GetNetTypeAttributeString();
						else
						{
							try { return _XsdDataContractSerializer.ReadObject(xe.CreateReader(), false); }
							catch { }
						}
					}
					break;
			}

			Type valueType = GetXsdType(declaredType);

			if (valueType == typeof(string))
				return xe.Value;

			try
			{
				return DBConvert.ChangeType(xe.Value, valueType);
			}
			catch
			{
				return xe.Value;
			}
		}

19 Source : XmlWriterExtensions.cs
with Apache License 2.0
from DataBooster

private static string GetNetTypeAttributeString(this XElement xe)
		{
			XAttribute declaredAttribute = xe.Attribute(XNsNet + NetTypeAttributeName);

			if (declaredAttribute == null)
				return null;
			else
				return declaredAttribute.Value;
		}

19 Source : AlienNode.cs
with Apache License 2.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            Port = Convert.ToInt32(element.Attribute( "Port" ).Value);
            Preplacedword = element.Attribute( "Preplacedword" ).Value;
        }

19 Source : NodeModbusTcpAline.cs
with Apache License 2.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            DTU = element.Attribute( "DTU" ).Value;
            Station = byte.Parse( element.Attribute( "Station" ).Value );
            IsAddressStartWithZero = bool.Parse( element.Attribute( "IsAddressStartWithZero" ).Value );
        }

19 Source : ModbusServerNode.cs
with Apache License 2.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            Port = Convert.ToInt32( element.Attribute( "Port" ).Value );
            CreateTime = DateTime.Parse( element.Attribute( "CreateTime" ).Value );
        }

19 Source : RegularNode.cs
with Apache License 2.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            RegularCode = int.Parse( element.Attribute( "TypeCode" ).Value );
            TypeLength = int.Parse( element.Attribute( "TypeLength" ).Value );
            Index = int.Parse( element.Attribute( "Index" ).Value );
        }

19 Source : HSharpNodeManager.cs
with Apache License 2.0
from dathlin

private void AddDeviceCore( NodeState parent, XElement device )
        {
            if (device.Name == "DeviceNode")
            {
                // 提取名称和描述信息
                string name = device.Attribute( "Name" ).Value;
                string description = device.Attribute( "Description" ).Value;

                // 创建OPC节点
                FolderState deviceFolder = CreateFolder( parent, device.Attribute( "Name" ).Value, device.Attribute( "Description" ).Value );
                // 添加Request
                foreach (var requestXml in device.Elements( "DeviceRequest" ))
                {
                    DeviceRequest deviceRequest = new DeviceRequest( );
                    deviceRequest.LoadByXmlElement( requestXml );


                    AddDeviceRequest( deviceFolder, deviceRequest );
                }


                IDeviceCore deviceReal = CreateNewByXml( device );
                if (deviceReal != null)
                {
                    deviceReal.OpcUaNode = deviceFolder.NodeId.ToString( );
                    AddDeviceCore( deviceReal );
                    deviceReal.WriteDeviceData = WriteDeviceData;
                    deviceReal.Name = name;
                    deviceReal.StartRead( );

                    // 显示系统所有的设备数量
                    Interlocked.Increment( ref deviceCount );
                    this.logNet?.WriteInfo( $"已发现 {deviceCount} 台设备,类型为{deviceReal.TypeName}" );
                }
            }
        }

19 Source : HSharpNodeManager.cs
with Apache License 2.0
from dathlin

private IDeviceCore CreateNewByXml(XElement device )
        {
            int deviceType = int.Parse( device.Attribute( "DeviceType" ).Value );

            if (deviceType == DeviceNode.ModbusTcpAlien)
            {
                return new DeviceModbusTcpAlien( device );
            }
            else if (deviceType == DeviceNode.ModbusTcpClient)
            {
                return new DeviceModbusTcp( device );
            }
            else if (deviceType == DeviceNode.MelsecMcQna3E)
            {
                NodeMelsecMc nodeMelsecMc = new NodeMelsecMc( );
                nodeMelsecMc.LoadByXmlElement( device );

                if (nodeMelsecMc.IsBinary)
                {
                    // 二进制通信
                    return new DeviceMelsecBinary( device );
                }
                else
                {
                    // ASCII通讯
                    return new DeviceMelsecAscii( device );
                }
            }
            else if(deviceType == DeviceNode.Omron)
            {
                return new DeviceOmron( device );
            }
            else if(deviceType == DeviceNode.SimplifyNet)
            {
                return new DeviceSimplifyNet( device );
            }
            else if(deviceType == DeviceNode.Siemens)
            {
                return new DeviceSiemens( device );
            }
            else
            {
                return null;
            }
        }

19 Source : SharpRegulars.cs
with Apache License 2.0
from dathlin

public void LoadRegulars()
        {
            if (File.Exists( filePath ))
            {
                XElement xElement = XElement.Load( filePath );
                if (xElement.Name == "Regulars")
                {
                    dictLock.Enter( );
                    sharpRegulars.Clear( );

                    foreach (var item in xElement.Elements( "NodeClreplaced" ))
                    {
                        string name = item.Attribute( "Name" ).Value;
                        List<RegularNode> regulars = new List<RegularNode>( );

                        foreach (var node in item.Elements( "RegularNode" ))
                        {
                            RegularNode tmp = new RegularNode( );
                            tmp.LoadByXmlElement( node );
                            regulars.Add( tmp );
                        }



                        if (!sharpRegulars.ContainsKey( name ))
                        {
                            sharpRegulars.Add( name, regulars );
                        }
                    }


                    dictLock.Leave( );
                }
            }
        }

19 Source : SharpNodeServer.cs
with GNU Lesser General Public License v3.0
from dathlin

private string[] GetXmlPath( XElement element )
        {
            List<string> paths = new List<string>( );
            while (true)
            {
                if(element != null)
                {
                    if(element.Attribute( "Name" ) == null)
                    {
                        break;
                    }
                    paths.Add( element.Attribute("Name").Value );
                    element = element.Parent;
                }
                else
                {
                    break;
                }
            }
            paths.Reverse( );
            return paths.ToArray( );
        }

19 Source : SharpNodeServer.cs
with GNU Lesser General Public License v3.0
from dathlin

private void AddDeviceCore( XElement device )
        {
            if (device.Name == "DeviceNode")
            {
                // 提取名称和描述信息
                string name = device.Attribute( "Name" ).Value;
                string description = device.Attribute( "Description" ).Value;


                DeviceCore deviceReal = Util.CreateFromXElement( device );
                if (deviceReal != null)
                {
                    // 添加所有Request的regular信息
                    foreach (var request in deviceReal.Requests)
                    {
                        if (!string.IsNullOrEmpty( request.PraseRegularCode ))
                        {
                            if (regularkeyValuePairs.ContainsKey( request.PraseRegularCode ))
                            {
                                request.RegularNodes = regularkeyValuePairs[request.PraseRegularCode];
                            }
                        }
                    }

                    deviceReal.WriteCustomerData = this.WriteCustomerData;
                    deviceReal.DeviceNodes = GetXmlPath( device );
                    deviceCores.Add( deviceReal );
                    if (this.dictDeviceCores.ContainsKey( deviceReal.UniqueId ))
                    {
                        this.logNet?.WriteError( "设备唯一码重复,无法添加集合,ID: " + deviceReal.UniqueId );
                    }
                    else
                    {
                        this.dictDeviceCores.Add( deviceReal.UniqueId, deviceReal );
                    }
                }
            }
        }

19 Source : DeviceNode.cs
with GNU Lesser General Public License v3.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            DeviceType = int.Parse( element.Attribute( "DeviceType" ).Value );
            ConnectTimeOut = int.Parse( element.Attribute( "ConnectTimeOut" ).Value );
            CreateTime = DateTime.Parse( element.Attribute( "CreateTime" ).Value );
            InstallationDate = DateTime.Parse( element.Attribute( "InstallationDate" ).Value );
        }

19 Source : NodeModbusTcpAline.cs
with GNU Lesser General Public License v3.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            DTU                    = element.Attribute( "DTU" ).Value;
            Station                = byte.Parse( element.Attribute( "Station" ).Value );
            IsAddressStartWithZero = bool.Parse( element.Attribute( "IsAddressStartWithZero" ).Value );
            DataFormat             = int.Parse( element.Attribute( "DataFormat" ).Value );
            IsStringReverse        = bool.Parse( element.Attribute( "IsStringReverse" ).Value );
        }

19 Source : NodeSimplifyNet.cs
with GNU Lesser General Public License v3.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            IpAddress = element.Attribute( "IpAddress" ).Value;
            Port = int.Parse( element.Attribute( "Port" ).Value );
            Token = new Guid( element.Attribute( "Token" ).Value );
        }

19 Source : NodeClass.cs
with GNU Lesser General Public License v3.0
from dathlin

public virtual void LoadByXmlElement( XElement element )
        {
            Name = element.Attribute( "Name" ).Value;
            Description = element.Attribute( "Description" ).Value;
        }

19 Source : DeviceRequest.cs
with GNU Lesser General Public License v3.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            Address = element.Attribute( "Address" ).Value;
            Length = ushort.Parse( element.Attribute( "Length" ).Value );
            CaptureInterval = int.Parse( element.Attribute( "CaptureInterval" ).Value );
            PraseRegularCode = element.Attribute( "PraseRegularCode" ).Value;
        }

19 Source : AlienServerNode.cs
with GNU Lesser General Public License v3.0
from dathlin

public override void LoadByXmlElement( XElement element )
        {
            base.LoadByXmlElement( element );
            Port = Convert.ToInt32( element.Attribute( "Port" ).Value );
            Preplacedword = element.Attribute( "Preplacedword" ).Value;
        }

See More Examples