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 View Source File : CheckCreateFile.cs
License : MIT License
Project Creator : 3RD-Dimension

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

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

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

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

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

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

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

19 View Source File : ViaCepWebservice.cs
License : MIT License
Project Creator : ACBrNet

private static List<ACBrEndereco> ConsultaCEP(string url)
		{
			try
			{
				var webRequest = (HttpWebRequest)WebRequest.Create(url);
				webRequest.ProtocolVersion = HttpVersion.Version10;
				webRequest.UserAgent = "Mozilla/4.0 (compatible; Synapse)";

				webRequest.KeepAlive = true;
				webRequest.Headers.Add(HttpRequestHeader.KeepAlive, "300");

				var response = webRequest.GetResponse();
				var xmlStream = response.GetResponseStream();
				var doc = XDoreplacedent.Load(xmlStream);

				var ret = new List<ACBrEndereco>();

				var rootElement = doc.Element("xmlcep");
				if (rootElement == null) return ret;

				if (rootElement.Element("enderecos") != null)
				{
					var element = rootElement.Element("enderecos");
					if (element == null) return ret;

					var elements = element.Elements("endereco");
					ret.AddRange(elements.Select(ProcessElement));
				}
				else
				{
					var endereco = ProcessElement(rootElement);
					ret.Add(endereco);
				}

				return ret;
			}
			catch (Exception e)
			{
				throw new ACBrException(e, "Erro ao consutar CEP.");
			}
		}

19 View Source File : SuppressionFile.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static HashSet<SuppressMessage> LoadMessages(ISuppressionFileSystemService fileSystemService, string path)
		{
			XDoreplacedent doreplacedent;

			lock (fileSystemService)
			{
				doreplacedent = fileSystemService.Load(path);
			}		

			if (doreplacedent == null)
			{
				return new HashSet<SuppressMessage>();
			}

			HashSet<SuppressMessage> suppressionMessages = new HashSet<SuppressMessage>();

			foreach (XElement suppressionMessageXml in doreplacedent.Root.Elements(SuppressMessageElement))
			{
				SuppressMessage? suppressMessage = SuppressMessage.MessageFromElement(suppressionMessageXml);

				if (suppressMessage != null)
				{
					suppressionMessages.Add(suppressMessage.Value);
				}
			}

			return suppressionMessages;
		}

19 View Source File : SetVersionInfoTask.cs
License : MIT License
Project Creator : adamecr

private static void SetProjectPropertyNode(XContainer projectNode, string nodeName, string nodeValue)
        {
            var propertyNode = projectNode
                .Elements("PropertyGroup")
                .SelectMany(it => it.Elements(nodeName))
                .SingleOrDefault();
            // If no  node exists, create it.
            if (propertyNode == null)
            {
                var propertyGroupNode = GetOrCreateElement(projectNode, "PropertyGroup");
                propertyNode = GetOrCreateElement(propertyGroupNode, nodeName);
            }
            propertyNode.SetValue(nodeValue);
        }

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : Adoxio

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

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

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

			if (layoutRow == null)
			{
				return;
			}

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

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

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static ICollection<FetchAttribute> GetAttributes(this XElement element)
		{
			if (element.Element("all-attributes") != null) return FetchAttribute.All;
			if (element.Element("no-attrs") != null) return FetchAttribute.None;
			return FetchAttribute.Parse(element.Elements("attribute"));
		}

19 View Source File : Fetch.cs
License : MIT License
Project Creator : Adoxio

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

			return new Fetch
			{
				MappingType = element.GetAttribute("mapping", Lookups.MappingTypeToText).GetValueOrDefault(),
				Version = element.GetAttribute("version"),
				PageSize = element.GetAttribute<int?>("count"),
				PageNumber = element.GetAttribute<int?>("page"),
				PagingCookie = element.GetAttribute("paging-cookie"),
				UtcOffset = element.GetAttribute<int?>("utc-offset"),

				Aggregate = element.GetAttribute<bool?>("aggregate"),
				Distinct = element.GetAttribute<bool?>("distinct"),
				MinActiveRowVersion = element.GetAttribute<bool?>("min-active-row-version"),
				OutputFormat = element.GetAttribute("output-format", Lookups.OutputFormatTypeToText),
				ReturnTotalRecordCount = element.GetAttribute<bool?>("returntotalrecordcount"),
				NoLock = element.GetAttribute<bool?>("no-lock"),

				Orders = Order.Parse(element.Elements("order")),
				Enreplacedy = FetchEnreplacedy.Parse(element.Element("enreplacedy")),

				Extensions = element.GetExtensions(),
			};
		}

19 View Source File : FetchEntity.cs
License : MIT License
Project Creator : Adoxio

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

			return new FetchEnreplacedy
			{
				Name = element.GetAttribute("name"),

				Attributes = element.GetAttributes(),

				Orders = Order.Parse(element.Elements("order")),
				Filters = Filter.Parse(element.Elements("filter")),
				Links = Link.Parse(element.Elements("link-enreplacedy")),

				Extensions = element.GetExtensions(),
			};
		}

19 View Source File : Filter.cs
License : MIT License
Project Creator : Adoxio

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

			return new Filter
			{
				Type = element.GetAttribute("type", Lookups.LogicalOperatorToText),
				Hint = element.GetAttribute<string>("hint"),
				IsQuickFindFields = element.GetAttribute<bool?>("isquickfindfields"),

				Conditions = Condition.Parse(element.Elements("condition")),
				Filters = Parse(element.Elements("filter")),

				Extensions = element.GetExtensions(),
			};
		}

19 View Source File : Link.cs
License : MIT License
Project Creator : Adoxio

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

			return new Link
			{
				Name = element.GetAttribute("name"),
				FromAttribute = element.GetAttribute("from"),
				ToAttribute = element.GetAttribute("to"),
				Alias = element.GetAttribute("alias"),
				Type = element.GetAttribute("link-type", Lookups.JoinOperatorToText),
				Visible = element.GetAttribute<bool?>("visible"),
				Intersect = element.GetAttribute<bool?>("intersect"),

				Attributes = element.GetAttributes(),

				Orders = Order.Parse(element.Elements("order")),
				Filters = Filter.Parse(element.Elements("filter")),
				Links = Parse(element.Elements("link-enreplacedy")),

				Extensions = element.GetExtensions(),
			};
		}

19 View Source File : Category.cs
License : MIT License
Project Creator : Adoxio

public static Category Parse(XElement element)
		{
			return new Category
			{
				Alias = element.GetAttribute("alias"),
				MeasureCollections = element.Elements("measurecollection").Select(MeasureCollection.Parse).ToList()
			};
		}

19 View Source File : DataDefinition.cs
License : MIT License
Project Creator : Adoxio

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

			var fetchCollectionElement = element.Element("fetchcollection");

			if (fetchCollectionElement == null)
			{
				return null;
			}

			var fetchElements = fetchCollectionElement.Elements("fetch");

			var categoryCollectionElement = element.Element("categorycollection");

			if (categoryCollectionElement == null)
			{
				return null;
			}

			var categoryElements = categoryCollectionElement.Elements("category");

			var categoryCollection = categoryElements.Select(Category.Parse).ToList();

			var fetchCollection = fetchElements.Select(Fetch.Parse).ToList();

			foreach (var fetch in fetchCollection)
			{
				// DateGrouping require us to also retrieve a datetime value so we can format series labels correctly. 
				// Grouping by day for example with a date like 9/23/2016 will result in the value 23 to be stored in the data.
				// We must manually add this aggregate attribute into the fetch so we get the actual date value 9/23/2016 displayed in the chart series.
				var dateGroupingAttributes = fetch.Enreplacedy.Attributes.Where(a => a.DateGrouping != null && a.DateGrouping.Value == DateGroupingType.Day).ToArray();
				foreach (var attribute in dateGroupingAttributes)
				{
					fetch.Enreplacedy.Attributes.Add(new FetchAttribute(attribute.Name,
						string.Format("{0}_dategroup_value", attribute.Alias), AggregateType.Max));
				}
			}

			return new DataDefinition
			{
				CategoryCollection = categoryCollection,
				FetchCollection = fetchCollection
			};
		}

19 View Source File : MeasureCollection.cs
License : MIT License
Project Creator : Adoxio

public static MeasureCollection Parse(XElement element)
		{
			return new MeasureCollection
			{
				Measures = element.Elements("measure").Select(Measure.Parse).ToList()
			};
		}

19 View Source File : Condition.cs
License : MIT License
Project Creator : Adoxio

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

			var elements = element.Elements("value").Select(e => e.Value as object).ToList();

			return new Condition
			{
				Column = element.GetAttribute("column"),
				EnreplacedyName = element.GetAttribute("enreplacedyname"),
				Attribute = element.GetAttribute("attribute"),
				Operator = element.GetAttribute<ConditionOperator>("operator", FetchXMLConditionalOperators.GetKeyByValue),
				Aggregate = element.GetAttribute("aggregate", Lookups.AggregateToText),
				Alias = element.GetAttribute("alias"),
				UiName = element.GetAttribute("uiname"),
				UiType = element.GetAttribute("uitype"),
				UiHidden = element.GetAttribute<bool?>("uihidden"),

				Value = element.GetAttribute("value"),

				Values = elements,

				Extensions = element.GetExtensions(),
			};
		}

19 View Source File : SavedQueryView.cs
License : MIT License
Project Creator : Adoxio

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

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

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

19 View Source File : SavedQueryColumnsGenerator.cs
License : MIT License
Project Creator : Adoxio

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

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

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

			return fields.ToArray();
		}

19 View Source File : CrmSavedQueryColumnsGenerator.cs
License : MIT License
Project Creator : Adoxio

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

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

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

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

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

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

			return fields.ToList();
		}

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

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

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

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

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

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

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

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

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

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

            return dungeon;
        }

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

            if ( monsterData == null )
                return null;

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

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

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

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

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

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

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

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

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

            if (creatureData == null)
                return null;

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

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

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

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

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

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

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

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

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

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

            if (plantData == null)
                return null;

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

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

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

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

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

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

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

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

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

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static Effect GetEffect( string effectName )
        {
            Effect effect = null;
            XElement effectData = null;

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

            // choose the right effect
            foreach (XElement e in effects)
                if (ReadAttribute(e.FirstAttribute) == effectName)
                    effectData = e;

            if (effectData == null)
                return null;

            // load the victim damage parameters
            int victimDmgMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_damage").FirstAttribute)),
                victimDmgMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_damage").LastAttribute)),
                victimMagickaDrainMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_drain").FirstAttribute)),
                victimMagickaDrainMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_drain").LastAttribute)),
                victimStaminaDrainMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_drain").FirstAttribute)),
                victimStaminaDrainMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_drain").LastAttribute));

            int[] victimResourceDamage = new int[3];
            victimResourceDamage[0] = Program.RNG.Next(victimDmgMin, victimDmgMax + 1);
            victimResourceDamage[1] = Program.RNG.Next(victimMagickaDrainMin, victimMagickaDrainMax + 1);
            victimResourceDamage[2] = Program.RNG.Next(victimStaminaDrainMin, victimStaminaDrainMax + 1);
            
            int victimHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_healing").FirstAttribute)),
                victimHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_healing").LastAttribute)),
                victimMagickaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_healing").FirstAttribute)),
                victimMagickaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_magicka_healing").LastAttribute)),
                victimStaminaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_healing").FirstAttribute)),
                victimStaminaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("victim_stamina_healing").LastAttribute));

            int[] victimResourceHealing = new int[3];
            victimResourceHealing[0] = Program.RNG.Next(victimHealingMin, victimHealingMax + 1);
            victimResourceHealing[1] = Program.RNG.Next(victimMagickaHealingMin, victimMagickaHealingMax + 1);
            victimResourceHealing[2] = Program.RNG.Next(victimStaminaHealingMin, victimStaminaHealingMax + 1);
            
            int userHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_healing").FirstAttribute)),
                userHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_healing").LastAttribute)),
                userMagickaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_magicka_healing").FirstAttribute)),
                userMagickaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_magicka_healing").LastAttribute)),
                userStaminaHealingMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_stamina_healing").FirstAttribute)),
                userStaminaHealingMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("user_stamina_healing").LastAttribute));

            int[] userResourceHealing = new int[3];
            userResourceHealing[0] = Program.RNG.Next(userHealingMin, userHealingMax + 1);
            userResourceHealing[1] = Program.RNG.Next(userMagickaHealingMin, userMagickaHealingMax + 1);
            userResourceHealing[2] = Program.RNG.Next(userStaminaHealingMin, userStaminaHealingMax + 1);

            // load the damage type
            Enum.TryParse(ReadElement(effectData.Element("victim_damage_type")), out DamageType victimDamageType);

            // load the status effect
            Enum.TryParse(ReadAttribute(effectData.Element("victim_status_effect").FirstAttribute), out StatusEffect statusEffect);
            
            // load the victim healing parameters

            // load the user healing parameters

            int turnsMin = System.Convert.ToInt32(ReadAttribute(effectData.Element("turns").FirstAttribute)), 
                turnsMax = victimDmgMax = System.Convert.ToInt32(ReadAttribute(effectData.Element("turns").LastAttribute));

            int chance = System.Convert.ToInt32(ReadAttribute(effectData.Element("inflict_chance").FirstAttribute));

            int turns = Program.RNG.Next(turnsMin, turnsMax + 1);

            effect = new Effect(effectName, victimResourceDamage, victimDamageType, statusEffect, victimResourceHealing, userResourceHealing, chance, turns);

            return effect;
        }

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

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

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

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

            return tip;
        }

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

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

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

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

            if (wEnchantData == null)
                return null;

            string name = enchantName;

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

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

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

            return wEnchant;
        }

19 View Source File : XmlMember.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

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

            HelpXml.AddRange(members);
        }

19 View Source File : XmlMember.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

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

19 View Source File : XmlApiResponseParser.cs
License : MIT License
Project Creator : Aircoookie

public static XmlApiResponse ParseApiResponse(string xml)
        {
            if (xml == null) return null;
            XmlApiResponse resp = new XmlApiResponse(); //XmlApiResponse object will contain parsed values
            try
            {
                XElement xe = XElement.Parse(xml);
                if (xe == null) return null;
                resp.Name = xe.Element("ds")?.Value;
                if (resp.Name == null) resp.Name = xe.Element("desc")?.Value; //try legacy XML element name (pre WLED 0.6.0)
                if (resp.Name == null) return null; //if we return at this point, parsing was unsuccessful (server likely not WLED device)

                string bri_s = xe.Element("ac")?.Value;
                if (bri_s == null) bri_s = xe.Element("act")?.Value; //try legacy XML element name (pre WLED 0.6.0)
                if (bri_s != null)
                {
                    int bri = 0;
                    Int32.TryParse(bri_s, out bri);
                    resp.Brightness = (byte)bri;
                    resp.IsOn = (bri > 0); //light is on if brightness > 0
                }

                double r = 0, g = 0, b = 0;
                int counter = 0;
                foreach (var el in xe.Elements("cl"))
                {
                    int co = 0;
                    Int32.TryParse(el?.Value, out co);
                    switch (counter)
                    {
                        case 0: r = co / 255.0; break;
                        case 1: g = co / 255.0; break;
                        case 2: b = co / 255.0; break;
                    }
                    counter++;
                }
                resp.LightColor = new Color(r, g, b);
                return resp;
            } catch
            {
                //Exceptions here indicate unsuccessful parsing
            }
            return null;
        }

19 View Source File : XMLStuff.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

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

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

            try
            {

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

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

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

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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

                    }
                }

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

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

19 View Source File : XMLStuff.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

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


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

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

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

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

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

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



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

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

19 View Source File : StatisticsCounter.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

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

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

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

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

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

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


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

                xdoc.Save(StatisticsFilePath);

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

19 View Source File : UPSProvider.cs
License : MIT License
Project Creator : alexeybusygin

private void ParseRatesResponseMessage(XDoreplacedent xDoc)
        {
            if (xDoc.Root != null)
            {
                var response = xDoc.Root.XPathSelectElement("Response");
                if (response != null)
                {
                    var responseErrors = response.Elements("Error");
                    foreach (var responseError in responseErrors)
                    {
                        AddError(new Error
                        {
                            Description = responseError.XPathSelectElement("ErrorDescription")?.Value,
                            Number = responseError.XPathSelectElement("ErrorCode")?.Value,
                        });
                    }
                }

                var ratedShipment = xDoc.Root.Elements("RatedShipment");
                foreach (var rateNode in ratedShipment)
                {
                    var name = rateNode.XPathSelectElement("Service/Code").Value;
                    AvailableService service;
                    if (_serviceCodes.ContainsKey(name))
                    {
                        service = (AvailableService) _serviceCodes[name];
                    }
                    else
                    {
                        continue;
                    }
                    if (((int) Services & service.EnumValue) != service.EnumValue)
                    {
                        continue;
                    }
                    var description = "";
                    if (_serviceCodes.ContainsKey(name))
                    {
                        description = _serviceCodes[name].ToString();
                    }
                    var totalCharges = Convert.ToDecimal(rateNode.XPathSelectElement("TotalCharges/MonetaryValue").Value);
                    var currencyCode = rateNode.XPathSelectElement("TotalCharges/CurrencyCode").Value;
                    if (UseNegotiatedRates)
                    {
                        var negotiatedRate = rateNode.XPathSelectElement("NegotiatedRates/NetSummaryCharges/GrandTotal/MonetaryValue");
                        if (negotiatedRate != null) // check for negotiated rate
                        {
                            totalCharges = Convert.ToDecimal(negotiatedRate.Value);
                            currencyCode = rateNode.XPathSelectElement("NegotiatedRates/NetSummaryCharges/GrandTotal/CurrencyCode").Value;
                        }
                    }

                    var date = rateNode.XPathSelectElement("GuaranteedDaysToDelivery").Value;
                    if (string.IsNullOrEmpty(date)) // no gauranteed delivery date, so use MaxDate to ensure correct sorting
                    {
                        date = DateTime.MaxValue.ToShortDateString();
                    }
                    else
                    {
                        date = (Shipment.Options.ShippingDate ?? DateTime.Now)
                            .AddDays(Convert.ToDouble(date)).ToShortDateString();
                    }
                    var deliveryTime = rateNode.XPathSelectElement("ScheduledDeliveryTime").Value;
                    if (string.IsNullOrEmpty(deliveryTime)) // no scheduled delivery time, so use 11:59:00 PM to ensure correct sorting
                    {
                        date += " 11:59:00 PM";
                    }
                    else
                    {
                        date += " " + deliveryTime.Replace("Noon", "PM").Replace("P.M.", "PM").Replace("A.M.", "AM");
                    }
                    var deliveryDate = DateTime.Parse(date);

                    AddRate(name, description, totalCharges, deliveryDate, new RateOptions()
                    {
                        SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
                    }, currencyCode);
                }
            }
        }

19 View Source File : AzureBlobFileStorage.cs
License : Apache License 2.0
Project Creator : aloneguid

private static IEnumerable<IOEntry> ConvertBatch(XElement blobs)
      {
         foreach(XElement blobPrefix in blobs.Elements("BlobPrefix"))
         {
            string name = blobPrefix.Element("Name").Value;
            yield return new IOEntry(name + IOPath.PathSeparatorString);
         }

         foreach(XElement blob in blobs.Elements("Blob"))
         {
            string name = blob.Element("Name").Value;
            var file = new IOEntry(name);

            foreach(XElement xp in blob.Element("Properties").Elements())
            {
               string pname = xp.Name.ToString();
               string pvalue = xp.Value;

               if(!string.IsNullOrEmpty(pvalue))
               {
                  if(pname == "Last-Modified")
                  {
                     file.LastModificationTime = DateTimeOffset.Parse(pvalue);
                  }
                  else if(pname == "Content-Length")
                  {
                     file.Size = long.Parse(pvalue);
                  }
                  else if(pname == "Content-MD5")
                  {
                     file.MD5 = pvalue;
                  }
                  else
                  {
                     file.Properties[pname] = pvalue;
                  }
               }
            }

            yield return file;
         }
      }

19 View Source File : BaseEngine.cs
License : MIT License
Project Creator : angelsix

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

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

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

19 View Source File : BaseEngine.cs
License : MIT License
Project Creator : angelsix

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

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

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

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

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

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

                    // No more processing
                    break;
                }
            }
        }

19 View Source File : TalkScheduleFileBased.cs
License : MIT License
Project Creator : AntonyCorbett

public static IEnumerable<TalkScheduleItem> Read(bool autoBell)
        {
            var result = new List<TalkScheduleItem>();

            if (Exists())
            {
                var path = GetFullPath();
                try
                {
                    var x = XDoreplacedent.Load(path);
                    var items = x.Root?.Element("items");
                    if (items != null)
                    {
                        var talkId = StartId;

                        foreach (XElement elem in items.Elements("item"))
                        {
                            var name = (string?) elem.Attribute("name") ?? $"Unknown name {talkId}";
                            var sectionNameInternal = (string?) elem.Attribute("section") ?? $"Unknown section {talkId}";
                            var sectionNameLocalised = (string?) elem.Attribute("section") ?? $"Unknown section {talkId}";

                            result.Add(new TalkScheduleItem(talkId, name, sectionNameInternal, sectionNameLocalised)
                            {
                                CountUp = AttributeToNullableBool(elem.Attribute("countup"), null),
                                OriginalDuration = AttributeToDuration(elem.Attribute("duration")),
                                Editable = AttributeToBool(elem.Attribute("editable"), false),
                                BellApplicable = AttributeToBool(elem.Attribute("bell"), false),
                                AutoBell = autoBell,
                                PersistFinalTimerValue = AttributeToBool(elem.Attribute("persist"), false)
                            });

                            ++talkId;
                        }
                    }
                }
                catch (Exception ex)
                {
                    result.Clear();
                    Log.Logger.Error(ex, $"Unable to read {path}");
                }
            }

            return result;
        }

19 View Source File : ProductManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

internal static void ApplyPatches(ProductInfo p, ApexSettings settings)
        {
            var client = new WebClient
            {
                BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
            };

            client.Headers.Add("Accept", "application/xml");
            var request = string.Format("api/Products/GetAvailablePatches?productName={0}&version={1}", p.generalName, p.installedVersion);
            var patchList = client.DownloadString(request);

            var doc = XDoreplacedent.Parse(patchList);
            var ns = XNamespace.Get(doc.Root.Attribute("xmlns").Value);
            var patchFiles = from s in XDoreplacedent.Parse(patchList).Root.Elements(ns + "string")
                             select s.Value;

            foreach (var patchFile in patchFiles)
            {
                var patchPath = string.Concat(settings.dataFolder, "/", patchFile);
                var url = string.Concat("content/patches/", patchFile);
                client.DownloadFile(url, patchPath);

                replacedetDatabase.ImportPackage(patchPath, false);
            }
        }

19 View Source File : ProductManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private static IEnumerable<ProductInfo> GetProductsInfo(ApexSettings settings, bool checkForUpdates)
        {
            var productsInfo = new List<ProductInfo>();

            //Get the currently installed products
            var installed = from a in AppDomain.CurrentDomain.Getreplacedemblies()
                            from attrib in a.GetCustomAttributes(typeof(ApexProductAttribute), true).Cast<ApexProductAttribute>()
                            select attrib;

            foreach (var p in installed)
            {
                var info = new ProductInfo
                {
                    product = p,
                    name = p.name,
                    generalName = p.generalName,
                    installedVersion = string.IsNullOrEmpty(p.version) ? null : new Version(p.version),
                    type = p.type
                };

                info.icon = GetIcon(info);
                info.changeLogPath = GetChangeLogPath(settings, info);
                productsInfo.Add(info);
            }

            //Check existence of product manifest
            var manifestPath = string.Concat(settings.dataFolder, "/Products.manifest");
            bool checkedForUpdates = checkForUpdates || settings.timeToUpdate || (!File.Exists(manifestPath) && settings.allowAutomaticUpdateCheck);
            if (checkedForUpdates)
            {
                DownloadLatest(settings, manifestPath);
            }

            //Read the product manifest
            if (!File.Exists(manifestPath))
            {
                return productsInfo;
            }

            var installedLookup = productsInfo.ToDictionary(p => p.generalName, StringComparer.OrdinalIgnoreCase);

            try
            {
                var productsXml = XDoreplacedent.Load(manifestPath);
                XNamespace ns = productsXml.Root.Attribute("xmlns").Value;

                foreach (var p in productsXml.Root.Elements(ns + "Product"))
                {
                    var productName = p.Element(ns + "name").Value;

                    ProductInfo info;
                    if (!installedLookup.TryGetValue(productName, out info))
                    {
                        info = new ProductInfo();
                        productsInfo.Add(info);
                        info.name = info.generalName = productName;
                    }

                    var versionString = p.Element(ns + "version").Value;
                    var patchString = p.Element(ns + "latestPatch").Value;

                    info.description = p.Element(ns + "description").Value;
                    info.newestVersion = string.IsNullOrEmpty(versionString) ? null : new Version(versionString);
                    info.latestPatch = string.IsNullOrEmpty(patchString) ? null : new Version(patchString);
                    info.productUrl = p.Element(ns + "productUrl").Value;
                    info.storeUrl = p.Element(ns + "storeUrl").Value;
                    info.type = (ProductType)Enum.Parse(typeof(ProductType), p.Element(ns + "type").Value);
                    info.icon = GetIcon(info);
                }
            }
            catch
            {
                //Just eat this, it should not happen, but if it does we do not want to impact the users, and there is no way to recover so...
            }

            //Apply update knowledge to list
            if (checkedForUpdates)
            {
                MarkPendingUpdates(settings, productsInfo);
            }

            return productsInfo;
        }

19 View Source File : CookieMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet

private static string FindClaimValue(Transaction transaction, string claimType)
        {
            XElement claim = transaction.ResponseElement.Elements("claim").SingleOrDefault(elt => elt.Attribute("type").Value == claimType);
            if (claim == null)
            {
                return null;
            }
            return claim.Attribute("value").Value;
        }

19 View Source File : GoogleOAuth2MiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet

public string FindClaimValue(string claimType)
            {
                XElement claim = ResponseElement.Elements("claim").SingleOrDefault(elt => elt.Attribute("type").Value == claimType);
                if (claim == null)
                {
                    return null;
                }
                return claim.Attribute("value").Value;
            }

19 View Source File : DiscoveryCmdlets.cs
License : Apache License 2.0
Project Creator : aws

internal static IEnumerable<ServiceInfo> GetServices()
        {
            using (var compressedStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("Amazon.PowerShell.CmdletsList.dat"))
            using (var stream = new GZipStream(compressedStream, CompressionMode.Decompress))
            using (var reader = new System.IO.StreamReader(stream))
            {
                var doc = XElement.Load(reader);
                foreach (var service in doc.Elements("Service"))
                {
                    var serviceName = service.Attribute("Name");
                    yield return new ServiceInfo
                    {
                        Name = service.Attribute("Name").Value,
                        Description = service.Attribute("Description").Value,
                        CmdletNounPrefix = service.Attribute("CmdletNounPrefix").Value,
                        ModuleName = service.Attribute("ModuleName").Value,
                        SDKreplacedemblyName = service.Attribute("SDKreplacedemblyName").Value,
                        SDKreplacedemblyVersion = service.Attribute("SDKreplacedemblyVersion").Value,
                        XmlElement = service
                    };

                    foreach (var cmdlet in service.Elements("Cmdlet"))
                    {
                        var cmdletName = cmdlet.Attribute("Name");
                    }
                }
            }
        }

19 View Source File : DiscoveryCmdlets.cs
License : Apache License 2.0
Project Creator : aws

private static IEnumerable<CmdletInfo> GetCmdlets(GetAWSServiceCmdlet.ServiceInfo service)
        {
            foreach (var cmdlet in service.XmlElement.Elements("Cmdlet"))
            {
                var cmdletName = cmdlet.Attribute("Name");
                yield return new CmdletInfo
                {
                    Name = cmdlet.Attribute("Name").Value,
                    Operations = cmdlet.Attribute("Operations").Value.Split(',')
                };
            }
        }

19 View Source File : ConfigMigrate.cs
License : Apache License 2.0
Project Creator : aws

private Configuration LoadWebConfig(string projectDir)
        {
            string webConfigFilePath = Path.Combine(projectDir, Constants.WebConfig);

            if (File.Exists(webConfigFilePath))
            {
                try
                {

                    XElement webConfigXml = XElement.Load(webConfigFilePath);
                    System.Xml.XmlDoreplacedent xmlDoreplacedent = new System.Xml.XmlDoreplacedent();
                    xmlDoreplacedent.Load(webConfigFilePath);

                    // Comment out connection strings if type has a configProtectionProvider
                    // This can comment out connection strings that do not have "EncryptedData"
                    IEnumerable<XElement> encryptedConnectionStringElement =
                        from element in webConfigXml.Elements("connectionStrings")
                        where (string)element.Attribute("configProtectionProvider") != null
                        select element;

                    if (encryptedConnectionStringElement.HasAny())
                    {
                        System.Xml.XmlNode elementToComment = xmlDoreplacedent.SelectSingleNode("/configuration/connectionStrings");
                        string commentContents = elementToComment.OuterXml;

                        // Its contents are the XML content of target node
                        System.Xml.XmlComment commentNode = xmlDoreplacedent.CreateComment(commentContents);

                        // Get a reference to the parent of the target node
                        System.Xml.XmlNode parentNode = elementToComment.ParentNode;

                        // Replace the target node with the comment
                        parentNode.ReplaceChild(commentNode, elementToComment);
                        xmlDoreplacedent.Save(webConfigFilePath);
                    }

                    var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = webConfigFilePath };
                    var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                    return configuration;
                }
                catch (Exception ex)
                {
                    LogHelper.LogError(ex, string.Format("Error processing web.config file {0}", webConfigFilePath));
                }
            }
            return null;
        }

19 View Source File : FileBlogService.cs
License : Apache License 2.0
Project Creator : aws

private static void LoadCategories(Post post, XElement doc)
        {
            var categories = doc.Element("categories");
            if (categories is null)
            {
                return;
            }

            post.Categories.Clear();
            categories.Elements("category").Select(node => node.Value).ToList().ForEach(post.Categories.Add);
        }

19 View Source File : FileBlogService.cs
License : Apache License 2.0
Project Creator : aws

private static void LoadComments(Post post, XElement doc)
        {
            var comments = doc.Element("comments");

            if (comments is null)
            {
                return;
            }

            foreach (var node in comments.Elements("comment"))
            {
                var comment = new Comment
                {
                    ID = ReadAttribute(node, "id"),
                    Author = ReadValue(node, "author"),
                    Email = ReadValue(node, "email"),
                    IsAdmin = bool.Parse(ReadAttribute(node, "isAdmin", "false")),
                    Content = ReadValue(node, "content"),
                    PubDate = DateTime.Parse(ReadValue(node, "date", "2000-01-01"),
                        CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal),
                };

                post.Comments.Add(comment);
            }
        }

19 View Source File : AppInsightsDataProvider.cs
License : MIT License
Project Creator : Azure

private string GetTagValue(string tagsXml, string key)
        {
            string tagValue = string.Empty;
            var xDoreplacedent = XDoreplacedent.Parse(tagsXml);
            XNamespace nsSys = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
            IEnumerable<XElement> tag = from el in xDoreplacedent.Elements(nsSys + "ArrayOfKeyValueOfstringstring").Elements()
                                        where (string)el.Element(nsSys + "Key") == key
                                        select el;

            if (tag != null && tag.Count() > 0)
            {
                var valueElement = tag.FirstOrDefault().Element(nsSys + "Value");
                if (valueElement != null)
                {
                    tagValue = valueElement.Value;
                }

            }
            return tagValue;
        }

19 View Source File : AuoHealMonitoringService.cs
License : MIT License
Project Creator : Azure

private bool IsAutoHealEnabled(XElement monitoringSection)
        {
            if (monitoringSection == default(XElement) || !monitoringSection.HasElements)
            {
                return false;
            }

            var triggers = monitoringSection.Elements("triggers").FirstOrDefault();
            var actions = monitoringSection.Elements("actions").FirstOrDefault();

            return
                triggers != default(XElement) && triggers.HasElements &&
                actions != default(XElement) && !string.IsNullOrWhiteSpace(GetAttributeValue(actions, "value"));
        }

See More Examples