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

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

1042 Examples 7

19 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 : SuppressionFileIOTests.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

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

			var messageToCheck = SuppressMessage.MessageFromElement(xElement);

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

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

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

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

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

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

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

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

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

            if (PartNuspecFiles == null)
            {
                Log.LogMessage("No source-only packages found");
                return true; //nothing to process
            }

            //process the source files
            foreach (var sourceFile in PartNuspecFiles)
            {
                var partNuspecFileNameFull = sourceFile.GetMetadata("FullPath");

                //Get the partial (partnuspec) file
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = partNuspecFileNameFull + ".tmp.nuspec";
                Log.LogMessage($"Loading {partNuspecFileNameFull}");
                var partNuspecFileContent = File.ReadAllText(partNuspecFileNameFull);
                partNuspecFileContent = partNuspecFileContent.Replace("%%CURRENT_VERSION%%", PackageVersionFull);
                var outXDoc = XDoreplacedent.Parse(partNuspecFileContent);
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                //Check package ID
                var packageId = metadataXElement.Element(ns + "id")?.Value;
                if (packageId == null) throw new Exception($"Can't find the package ID for {partNuspecFileNameFull}");

                //Process version - global version from solution of base version from partial file
                var versionOriginal = GetOrCreateElement(metadataXElement, "version", ns)?.Value;
                var version = PackageVersionFull;
                if (!string.IsNullOrEmpty(versionOriginal))
                {
                    //base version set in NuProp
                    //get ext version from PackageVersionFull
                    //0.1.0-dev.441.181206212308+53.master.37f08fc-dirty
                    //0.1.0+442.181206212418.master.37f08fc-dirty
                    var idx = 0;
                    while (char.IsDigit(PackageVersionFull[idx]) || PackageVersionFull[idx] == '.')
                    {
                        idx++;
                    }

                    version = versionOriginal + PackageVersionFull.Substring(idx);
                }

                //Enrich the NuSpec
                SetOrCreateElement(metadataXElement, "version", ns, version);
                SetOrCreateElement(metadataXElement, "authors", ns, Authors);
                SetOrCreateElement(metadataXElement, "replacedle", ns, packageId);
                SetOrCreateElement(metadataXElement, "owners", ns, Authors);
                SetOrCreateElement(metadataXElement, "description", ns, $"Source only package {packageId}", false); //don't override if exists
                SetOrCreateElement(metadataXElement, "requireLicenseAcceptance", ns, PackageRequireLicenseAcceptance);
                if (!string.IsNullOrEmpty(PackageLicense))
                {
                    SetOrCreateElement(metadataXElement, "license", ns, PackageLicense).
                        Add(new XAttribute("type","expression"));
                }
                else
                {
                    SetOrCreateElement(metadataXElement, "licenseUrl", ns, PackageLicenseUrl);
                }
                SetOrCreateElement(metadataXElement, "projectUrl", ns, PackageProjectUrl);
                SetOrCreateElement(metadataXElement, "iconUrl", ns, PackageIconUrl);
                SetOrCreateElement(metadataXElement, "copyright", ns, Copyright);
                SetOrCreateElement(metadataXElement, "developmentDependency", ns, "true");
                GetEmptyOrCreateElement(metadataXElement, "repository", ns).
                                    Add(new XAttribute("url", RepositoryUrl),
                                        new XAttribute("type", "git"),
                                        new XAttribute("branch", GitBranch),
                                        new XAttribute("commit", GitCommit));

                //Save the temporary NuSpec file
                var outXDocStr = outXDoc.ToString();
                File.WriteAllText(outFile, outXDocStr);
                Log.LogMessage($"Generated source only nuspec file {outFile}");
            }

            return true;
        }

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

private static XElement GetOrCreateElement(XContainer container, string name, XNamespace ns)
        {
            var element = container.Element(ns + name);
            if (element != null) return element;

            element = new XElement(ns + name);
            container.Add(element);
            return element;
        }

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

private static XElement GetOrCreateElement(XContainer container, string name)
        {
            var element = container.Element(name);
            if (element != null) return element;

            element = new XElement(name);
            container.Add(element);
            return element;
        }

19 View Source File : Extensions.cs
License : BSD 2-Clause "Simplified" License
Project Creator : adospace

public static string ElementValue(this XElement element, string name, string defaultValue = null)
        {
            var child = element.Element(name);
            if (child != null)
                return child.Value;

            return defaultValue;
        }

19 View Source File : Extensions.cs
License : BSD 2-Clause "Simplified" License
Project Creator : adospace

public static T ElementValue<T>(this XElement element, string name, Func<string, T> parseFunc, T defaultValue = default(T))
        {
            var child = element.Element(name);
            if (child != null)
                return parseFunc(child.Value);

            return defaultValue;
        }

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 : FetchXmlResultsFilter.cs
License : MIT License
Project Creator : Adoxio

public string Aggregate(string fetchXml, string primaryKeyFieldName, params string[] fields)
		{
			var fetchXmlParsed = XDoreplacedent.Parse(fetchXml);
			var inputResults = fetchXmlParsed.Descendants("result").ToList();

			if (inputResults.Count == 0)
			{
				return fetchXml;
			}

			var aggregatedResults = new Dictionary<string, XElement>();
			var parsedResultSet = new FetchXmlResultSet(fetchXml);

			bool isFirstPage = this.lastResultOnPage == null;
			bool isLastPage = !parsedResultSet.MoreRecords;

			//// Check if last result of last page and first result of this page are the same article.
			//// If not, we need to add the aggregated result from last page during this round.
			//// If so, the past CAL/product ids should still be stored and we'll just add to 
			if (!isFirstPage)
			{
				var firstId = inputResults.First().Descendants(primaryKeyFieldName).FirstOrDefault().Value;
				var previousPageLastId = this.lastResultOnPage.Descendants(primaryKeyFieldName).FirstOrDefault().Value;
				if (firstId != previousPageLastId)
				{
					aggregatedResults[previousPageLastId] = this.lastResultOnPage;
				}
			}
			var lastId = inputResults.Descendants(primaryKeyFieldName).FirstOrDefault().Value;

			var collectionOfFields = fields.Select(fieldName => new RelatedField(fieldName)).ToList();

			//// Iterating through fetchXml retrieving multiple related fields
			foreach (var resultNode in inputResults)
			{
				var primaryKeyFieldNode = resultNode.Descendants(primaryKeyFieldName).FirstOrDefault();
				if (primaryKeyFieldNode == null) { return fetchXml; }

				////Retrieving fields
				collectionOfFields.ForEach(field => this.GetRelatedFields(resultNode, field, primaryKeyFieldNode.Value));
				////Removing duplicate nodes
				aggregatedResults[primaryKeyFieldNode.Value] = resultNode;
			}

			var node = inputResults.FirstOrDefault();
			if (node == null)
			{
				return fetchXml;
			}
			var parentNode = node.Parent;
			if (parentNode == null)
			{
				return fetchXml;
			}

			fetchXmlParsed.Descendants("result").Remove();

			//// Inserting retrieved above related fields and deduplicated results.
			collectionOfFields.ForEach(field => this.InsertRelatedFields(aggregatedResults, field));

			//// Remove and store the last aggregated result, as this might be the same article as the first result on the 
			//// next page.
			this.lastResultOnPage = aggregatedResults[lastId];
			if (!isLastPage)
			{
				aggregatedResults.Remove(lastId);
			}

			fetchXmlParsed.Element(parentNode.Name).Add(aggregatedResults.Values);
			return fetchXmlParsed.ToString();
		}

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 : 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 : SubjectControlTemplate.cs
License : MIT License
Project Creator : Adoxio

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

			var context = CrmConfigurationManager.CreateContext();

			var service = CrmConfigurationManager.CreateService();

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

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

			List<Enreplacedy> subjects;

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

				var xElement = XElement.Parse(fetchXML);

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

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

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

					if (enreplacedyElement == null)
					{
						return;
					}

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

					enreplacedyElement.Add(p);

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

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

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

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

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

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

				var parentId = parent.Id;

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

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

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

protected virtual Fetch ToFetch(DataSourceSelectArguments arguments, string fetchXml)
		{
			Fetch expression = null;

			// the SortExpression has high priority, apply it to the query
			AppendSortExpressionToQuery(arguments.SortExpression, order =>
			{
				var xml = XElement.Parse(fetchXml);
				var enreplacedyElement = xml.Element("enreplacedy");

				if (enreplacedyElement != null)
				{
					var orderElement = new XElement("order",
						new XAttribute("attribute", order.AttributeName),
						new XAttribute("descending", order.OrderType == OrderType.Descending));

					enreplacedyElement.Add(orderElement);

					expression = Fetch.Parse(xml);
				}
			});

			return expression ?? Fetch.Parse(fetchXml);
		}

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 : CrmDataSourceView.cs
License : MIT License
Project Creator : Adoxio

protected virtual FetchExpression ToFetchExpression(DataSourceSelectArguments arguments, string fetchXml)
		{
			FetchExpression expression = null;

			// the SortExpression has high priority, apply it to the query
			AppendSortExpressionToQuery(arguments.SortExpression, order =>
			{
				var xml = XElement.Parse(fetchXml);
				var enreplacedyElement = xml.Element("enreplacedy");

				if (enreplacedyElement != null)
				{
					var orderElement = new XElement("order",
						new XAttribute("attribute", order.AttributeName),
						new XAttribute("descending", order.OrderType == OrderType.Descending));

					enreplacedyElement.Add(orderElement);

					expression = new FetchExpression(xml.ToString());
				}
			});

			return expression ?? new FetchExpression(fetchXml);
		}

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 : SetupManager.cs
License : MIT License
Project Creator : Adoxio

private static string GetText(XContainer xml, string tagName)
		{
			var element = xml.Element(tagName);
			return element != null ? element.Value : null;
		}

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr

public void readxml()
        {
            statuslabel.Content = "Reading XML File...";

            string xmldir = AppDomain.CurrentDomain.BaseDirectory + @"\\tmp";
            string[] xmlfile = Directory.GetFiles(xmldir, "*.xml");

            if (xmlfile.Length != 1)
            {
                System.Windows.MessageBox.Show("There is no file to patch within your NSP file!");
                return;
            }

            XDoreplacedent xdoc = XDoreplacedent.Load(xmlfile[0]);
            foreach (var order in xdoc.Descendants("ContentMeta"))
            {
                string mrmk = order.Element("KeyGenerationMin").Value;
                {
                    keylabel.Content = mrmk;
                }

                string tid = order.Element("Id").Value;
                {
                    tidlabel.Content = tid.Substring(2);
                }
            }

            if (keylabel.Content.Equals(null))
            {
                fwlabel.Content = "???";

                DialogResult uspg = System.Windows.Forms.MessageBox.Show("This NSP is not supported!",
                "Error", MessageBoxButtons.OK,
                MessageBoxIcon.Error);

                if (uspg == System.Windows.Forms.DialogResult.OK)
                    return;
            }

            if (keylabel.Content.Equals("0"))
            {
                fwlabel.Content = "all";
            }

            if (keylabel.Content.Equals("1"))
            {
                fwlabel.Content = "1.0.0";
            }

            if (keylabel.Content.Equals("2"))
            {
                fwlabel.Content = "3.0.0";
            }

            if (keylabel.Content.Equals("3"))
            {
                fwlabel.Content = "3.0.1";
            }

            if (keylabel.Content.Equals("4"))
            {
                fwlabel.Content = "4.0.0";
            }

            if (keylabel.Content.Equals("5"))
            {
                fwlabel.Content = "5.0.0";
            }

            if (keylabel.Content.Equals("6"))
            {
                fwlabel.Content = "???";

                DialogResult uspg = System.Windows.Forms.MessageBox.Show("This NSP is not supported yet!",
              "Error", MessageBoxButtons.OK,
               MessageBoxIcon.Error);

              if (uspg == System.Windows.Forms.DialogResult.OK)
              return;
            }
             
            patchxml();
        }

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 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 : 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 : 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 : UpdateChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private static void NextUpdateCallback(Popup p)
        {
            if (p.IndexOfGivenAnswer == 0)
            {
                Game.LogTrivial("Continue pressed");
                Index++;
                if (PluginsDownloadLink.Count > Index)
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Update " + (Index + 1) + ": " + PluginsDownloadLink[Index].Item1, new List<string>() { "Continue", "Go to download page" },
                        false, false, NextUpdateCallback);
                    pop.Display();
                }
                else
                {
                    Popup pop = new Popup("Albo1125.Common Update Check", "Please install updates to maintain stability and don't request support for old versions.",
                        new List<string>() { "-", "Open installation/troubleshooting video tutorial", "Continue to game.", "Delay next update check by a week.", "Delay next update check by a month.",
                            "Fully disable update checks (not recommended)." }, false, false, NextUpdateCallback);
                    pop.Display();
                }
            }
            else if (p.IndexOfGivenAnswer == 1)
            {
                Game.LogTrivial("GoToDownload pressed.");
                if (PluginsDownloadLink.Count > Index && Index >= 0)
                {
                    System.Diagnostics.Process.Start(PluginsDownloadLink[Index].Item2);
                }
                else
                {
                    System.Diagnostics.Process.Start("https://youtu.be/af434m72rIo?list=PLEKypmos74W8PMP4k6xmVxpTKdebvJpFb");
                }
                p.Display();
            }
            else if (p.IndexOfGivenAnswer == 2)
            {
                Game.LogTrivial("ExitButton pressed.");
            }
            else if (p.IndexOfGivenAnswer == 3)
            {
                Game.LogTrivial("Delay by week pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(6);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 4)
            {
                Game.LogTrivial("Delay by month pressed");
                DateTime NextUpdateCheckDT = DateTime.Now.AddMonths(1);
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
            }
            else if (p.IndexOfGivenAnswer == 5)
            {
                Game.LogTrivial("Disable Update Checks pressed.");
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                Popup pop = new Popup("Albo1125.Common Update Check", "Update checking has been disabled for this version of Albo1125.Common." +
                    "To re-enable it, delete the Albo1125.Common folder from your Grand Theft Auto V folder. Please do not request support for old versions.", false, true);
                pop.Display();
            }
        }

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

public static void InitialiseUpdateCheckingProcess()
        {
            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Starting update checks.");
            Directory.CreateDirectory("Albo1125.Common/UpdateInfo");
            if (!File.Exists("Albo1125.Common/CommonVariables.xml"))
            {
                new XDoreplacedent(
                        new XElement("CommonVariables")
                    )
                    .Save("Albo1125.Common/CommonVariables.xml");
            }
            try
            {
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                if (!string.IsNullOrWhiteSpace((string)CommonVariablesDoc.Root.Element("NextUpdateCheckDT")))
                {

                    try
                    {
                        if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value == replacedembly.GetExecutingreplacedembly().GetName().Version.ToString())
                        {
                            Game.LogTrivial("Albo1125.Common update checking has been disabled. Skipping checks.");
                            Game.LogTrivial("Albo1125.Common note: please do not request support for old versions.");
                            return;
                        }
                        DateTime UpdateCheckDT = DateTime.FromBinary(long.Parse(CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value));
                        if (DateTime.Now < UpdateCheckDT)
                        {

                            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Not checking for updates until " + UpdateCheckDT.ToString());
                            return;
                        }
                    }
                    catch (Exception e) { Game.LogTrivial(e.ToString()); Game.LogTrivial("Albo1125.Common handled exception. #1"); }

                }

                
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(1);
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                GameFiber.StartNew(delegate
                {


                    GetUpdateNodes();
                    foreach (UpdateEntry entry in AllUpdateEntries.ToArray())
                    {
                        CheckForModificationUpdates(entry.Name, new Version(FileVersionInfo.GetVersionInfo(entry.Path).FileVersion), entry.FileID, entry.DownloadLink);
                    }
                    if (PluginsDownloadLink.Count > 0) { DisplayUpdates(); }
                    Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Update checks complete.");
                });
            }
            catch (System.Xml.XmlException e)
            {
                Game.LogTrivial(e.ToString());
                Game.DisplayNotification("Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common");
                Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Albo1125.Common", "Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common", false);
                throw e;
            }

            



        }

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

public static void VerifyXmlNodeExists(string Name, string FileID, string DownloadLink, string Path)
        {        
            Game.LogTrivial("Albo1125.Common verifying update entry for " + Name);
            XDoreplacedent xdoc =

                    new XDoreplacedent(
                            new XElement("UpdateEntry")
                        );
                        
            try
            {
                Directory.CreateDirectory("Albo1125.Common/UpdateInfo");

                xdoc.Root.Add(new XElement("Name"));
                xdoc.Root.Element("Name").Value = XmlConvert.EncodeName(Name);

                xdoc.Root.Add(new XElement("FileID"));
                xdoc.Root.Element("FileID").Value = FileID;

                xdoc.Root.Add(new XElement("DownloadLink"));
                xdoc.Root.Element("DownloadLink").Value = XmlConvert.EncodeName(DownloadLink);

                xdoc.Root.Add(new XElement("Path"));

                xdoc.Root.Element("Path").Value = XmlConvert.EncodeName(Path);

                xdoc.Save("Albo1125.Common/UpdateInfo/" + Name + ".xml");
                
            }
            catch (System.Xml.XmlException e)
            {
                Game.LogTrivial(e.ToString());
                Game.DisplayNotification("Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common");
                ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Albo1125.Common", "Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common", false);
                throw e;
            }

        }

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

private static void GetUpdateNodes()
        {
            IEnumerable<string> XMLUpdateFiles = Directory.EnumerateFiles("Albo1125.Common/UpdateInfo", "*.xml");
            foreach (string xmlnode in XMLUpdateFiles)
            {
                XDoreplacedent xdoc = XDoreplacedent.Load(xmlnode);
                if (IsUpdateNodeValid(xdoc.Root))
                {
                    if (File.Exists(XmlConvert.DecodeName(xdoc.Root.Element("Path").Value.Trim())))
                    {
                        AllUpdateEntries.Add(new UpdateEntry()
                        {
                            Name = XmlConvert.DecodeName(xdoc.Root.Element("Name").Value.Trim()),
                            FileID = xdoc.Root.Element("FileID").Value.Trim(),
                            DownloadLink = XmlConvert.DecodeName(xdoc.Root.Element("DownloadLink").Value.Trim()),
                            Path = XmlConvert.DecodeName(xdoc.Root.Element("Path").Value.Trim()),

                        });
                    }
                }
                xdoc = null;


            }
            

        }

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

private static void LoadCourtCasesFromXMLFile(string File)
        {
            try
            {
                XDoreplacedent xdoc = XDoreplacedent.Load(File);
                char[] trim = new char[] { '\'', '\"', ' ' };
                List<CourtCase> AllCourtCases = xdoc.Descendants("CourtCase").Select(x => new CourtCase()
                {
                    SuspectName = ((string)x.Element("SuspectName").Value).Trim(trim),
                    SuspectDOB = DateTime.FromBinary(long.Parse(x.Element("SuspectDOB").Value)),
                    Crime = ((string)x.Element("Crime").Value).Trim(trim),
                    CrimeDate = DateTime.FromBinary(long.Parse(x.Element("CrimeDate").Value)),
                    GuiltyChance = int.Parse(x.Element("GuiltyChance") != null ?  ((string)x.Element("GuiltyChance").Value).Trim(trim) : "100"),
                    CourtVerdict = ((string)x.Element("CourtVerdict").Value).Trim(trim),
                    ResultsPublishTime = DateTime.FromBinary(long.Parse(x.Element("ResultsPublishTime").Value)),
                    ResultsPublished = bool.Parse(((string)x.Element("Published").Value).Trim(trim)),
                    ResultsPublishedNotificationShown = bool.Parse(((string)x.Element("ResultsPublishedNotificationShown").Value).Trim(trim))

                }).ToList<CourtCase>();

                foreach (CourtCase courtcase in AllCourtCases)
                {
                    courtcase.AddToCourtsMenuAndLists();
                }

            }
            catch (System.Threading.ThreadAbortException e) { }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered an exception reading \'" + File + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Error reading CourtCases.xml. Setting default values.");
            }
            finally
            {
                LoadingXMLFileCases = false;
            }


        }

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

private static void AddCourtCaseToXMLFile(string File, CourtCase ccase)
        {
            try
            {

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


                XElement LSPDFRPlusElement = xdoc.Element("LSPDFRPlus");
                XElement CcaseElement = new XElement("CourtCase",
                    new XAttribute("ID", ccase.XMLIdentifier),
                    new XElement("SuspectName", ccase.SuspectName),
                    new XElement("SuspectDOB", ccase.SuspectDOB.ToBinary()),
                    new XElement("Crime", ccase.Crime),
                    new XElement("CrimeDate", ccase.CrimeDate.ToBinary()),
                    new XElement("GuiltyChance", ccase.GuiltyChance.ToString()),
                    new XElement("CourtVerdict", ccase.CourtVerdict),
                    new XElement("ResultsPublishTime", ccase.ResultsPublishTime.ToBinary()),
                    new XElement("Published", ccase.ResultsPublished.ToString()),
                    new XElement("ResultsPublishedNotificationShown", ccase.ResultsPublishedNotificationShown.ToString()));
                LSPDFRPlusElement.Add(CcaseElement);
                xdoc.Save(File);


            }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered an exception writing a court case to \'" + File + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Error while working with CourtCases.xml.");
            }
        }

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 : DisplayHandler.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private static List<ButtonPage> SetupButtonPage(string file)
        {
            int ItemCount = 1;
            int Page = 1;
            List<Button> AllButtons = new List<Button>();

            try
            {
                if(!File.Exists(file))
                {
                    generateButtonXML(file);
                    firstTimeLaunch = true;
                }
                XDoreplacedent xdoc = XDoreplacedent.Load(file);
                
                foreach (XElement x in xdoc.Root.Descendants("Button"))
                {
                    if (!string.IsNullOrWhiteSpace((string)x.Element("Plugin")) && !string.IsNullOrWhiteSpace((string)x.Element("Name")) && !string.IsNullOrWhiteSpace((string)x.Element("Enabled")))
                    {
                        Button b = new Button(x.Element("Plugin").Value, x.Element("Name").Value, ItemCount, bool.Parse(x.Element("Enabled").Value));
                        if (!AllButtons.Contains(b))
                        {
                            AllButtons.Add(b);
                            ItemCount++;
                            if (ItemCount > ButtonsPerPage)
                            {
                                Page++;
                                ItemCount = 1;
                            }
                        }

                    }
                    else
                    {
                        Game.LogTrivial("PoliceSmartRadio: button in " + file + " has no Plugin or Name. Skipping.");
                    }
                    
                }
                Game.LogTrivial("Allbuttons ln: " + AllButtons.Count);
            }
            catch (Exception e)
            {
                Game.LogTrivial(e.ToString());
            }

            List<ButtonPage> ButtonsPages = new List<ButtonPage>();
            int addingToPage = 0;
            int itemsOnPage = 0;
            foreach (Button b in AllButtons)
            {
                if (ButtonsPages.Count <= addingToPage)
                {
                    ButtonsPages.Add(new ButtonPage());
                }
                ButtonsPages[addingToPage].Buttons.Add(b);
                itemsOnPage++;
                if (itemsOnPage == ButtonsPerPage)
                {
                    addingToPage++;
                    itemsOnPage = 0;
                }
            }
            AllButtonPages.AddRange(ButtonsPages);
            if (ButtonsPages.Count == 0) { ButtonsPages.Add(new ButtonPage()); }
            return ButtonsPages;           
        }

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

protected void ParseErrors(XElement response)
        {
            if (response?.Descendants("Error")?.Any() ?? false)
            {
                var errors = response
                    .Descendants("Error")
                    .Select(item => new Error()
                    {
                        Description = item.Element("Description")?.Value?.ToString(),
                        Source = item.Element("Source")?.Value?.ToString(),
                        HelpContext = item.Element("HelpContext")?.Value?.ToString(),
                        HelpFile = item.Element("HelpFile")?.Value?.ToString(),
                        Number = item.Element("Number")?.Value?.ToString()
                    });

                foreach (var err in errors)
                {
                    AddError(err);
                }
            }
        }

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

private void ParseResult(string response)
        {
            var doreplacedent = XDoreplacedent.Load(new StringReader(response));

            var rates = doreplacedent.Descendants("Service").GroupBy(item => (string) item.Element("SvcDescription")).Select(g => new {Name = g.Key, TotalCharges = g.Sum(x => Decimal.Parse((string) x.Element("Postage")))});

            foreach (var r in rates)
            {
                var name = Regex.Replace(r.Name, "<.*gt;", "");

                if (_service == name || _service == "ALL")
                {
                    AddRate(name, string.Concat("USPS ", name), r.TotalCharges, DateTime.Now.AddDays(30), null, USPSCurrencyCode);
                }
            }

            //check for errors
            ParseErrors(doreplacedent.Root);
        }

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

private void ParseResult(string response, IList<SpecialServices> includeSpecialServiceCodes = null)
        {
            var doreplacedent = XElement.Parse(response, LoadOptions.None);

            var rates = from item in doreplacedent.Descendants("Postage")
                group item by (string) item.Element("MailService")
                into g
                select new {Name = g.Key,
                            TotalCharges = g.Sum(x => decimal.Parse((string) x.Element("Rate"))),
                            TotalCommercialCharges = g.Sum(x => decimal.Parse((string) x.Element("CommercialRate") ?? "0")),
                            DeliveryDate = g.Select(x => (string) x.Element("CommitmentDate")).FirstOrDefault(),
                            SpecialServices = g.Select(x => x.Element("SpecialServices")).FirstOrDefault() };

            foreach (var r in rates)
            {
                //string name = r.Name.Replace(REMOVE_FROM_RATE_NAME, string.Empty);
                var name = Regex.Replace(r.Name, "<.*>", "");
                var additionalCharges = 0.0m;

                if (includeSpecialServiceCodes != null && includeSpecialServiceCodes.Count > 0 && r.SpecialServices != null)
                {
                    var specialServices = r.SpecialServices.XPathSelectElements("SpecialService").ToList();
                    if (specialServices.Count > 0)
                    {
                        foreach (var specialService in specialServices)
                        {
                            var serviceId = (int)specialService.Element("ServiceID");
                            var price = decimal.Parse((string) specialService.Element("Price"));

                            if (includeSpecialServiceCodes.Contains((SpecialServices)serviceId))
                                additionalCharges += price;
                        }
                    }
                }

                var isNegotiatedRate = _service == Services.Online && r.TotalCommercialCharges > 0;
                var totalCharges = isNegotiatedRate ? r.TotalCommercialCharges : r.TotalCharges;

                if (r.DeliveryDate != null && DateTime.TryParse(r.DeliveryDate, out DateTime deliveryDate))
                {
                    var rateOptions = new RateOptions()
                    {
                        SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
                    };
                    AddRate(name, string.Concat("USPS ", name), totalCharges + additionalCharges, deliveryDate, rateOptions, USPSCurrencyCode);
                }
                else
                {
                    AddRate(name, string.Concat("USPS ", name), totalCharges + additionalCharges, DateTime.Now.AddDays(30), null, USPSCurrencyCode);
                }
            }

            //check for errors
            ParseErrors(doreplacedent);
        }

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

private void ParseRates(IEnumerable<XElement> rates)
        {
            var includedServices = _configuration.ServicesIncluded;
            var excludedServices = _configuration.ServicesExcluded;

            foreach (var rateNode in rates)
            {
                var serviceCode = rateNode.Element("GlobalProductCode")?.Value;
                if (string.IsNullOrEmpty(serviceCode) || !AvailableServices.ContainsKey(serviceCode[0]))
                {
                    AddInternalError($"Unknown DHL Global Product Code: {serviceCode}");
                    continue;
                }
                if ((includedServices.Any() && !includedServices.Contains(serviceCode[0])) ||
                    (excludedServices.Any() && excludedServices.Contains(serviceCode[0])))
                {
                    continue;
                }

                var name = rateNode.Element("ProductShortName")?.Value;
                var description = AvailableServices[serviceCode[0]];

                var totalCharges = Convert.ToDecimal(rateNode.Element("ShippingCharge")?.Value, CultureInfo.InvariantCulture);
                var currencyCode = rateNode.Element("CurrencyCode")?.Value;

                var deliveryDateValue = rateNode.XPathSelectElement("DeliveryDate")?.Value;
                var deliveryTimeValue = rateNode.XPathSelectElement("DeliveryTime")?.Value;

                if (!DateTime.TryParse(deliveryDateValue, out DateTime deliveryDate))
                    deliveryDate = DateTime.MaxValue;

                if (!string.IsNullOrEmpty(deliveryTimeValue) && deliveryTimeValue.Length >= 4)
                {
                    // Parse PTxxH or PTxxHyyM to time
                    var indexOfH = deliveryTimeValue.IndexOf('H');
                    if (indexOfH >= 3)
                    {
                        var hours = int.Parse(deliveryTimeValue.Substring(2, indexOfH - 2), CultureInfo.InvariantCulture);
                        var minutes = 0;

                        var indexOfM = deliveryTimeValue.IndexOf('M');
                        if (indexOfM > indexOfH)
                        {
                            minutes = int.Parse(deliveryTimeValue.Substring(indexOfH + 1, indexOfM - indexOfH - 1), CultureInfo.InvariantCulture);
                        }

                        deliveryDate = deliveryDate.Date + new TimeSpan(hours, minutes, 0);
                    }
                }

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

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

private void ParseErrors(IEnumerable<XElement> errors)
        {
            foreach (var errorNode in errors)
            {
                AddError(new Error()
                {
                    Number = errorNode.Element("ConditionCode")?.Value,
                    Description = errorNode.Element("ConditionData")?.Value
                });
            }
        }

19 View Source File : DataConnectionConfiguration.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public string GetSelectedSource()
		{
			try
			{
				XElement xElem = this.RootElement.Element("DataSourceSelection");
				XElement sourceElem = xElem.Element("SelectedSource");
				if (sourceElem != null)
				{
					return sourceElem.Value as string;
				}
			}
			catch
			{
				return null;
			}
			return null;
		}

19 View Source File : DataConnectionConfiguration.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public string GetSelectedProvider()
		{
			try
			{
				XElement xElem = this.RootElement.Element("DataSourceSelection");
				XElement providerElem = xElem.Element("SelectedProvider");
				if (providerElem != null)
				{
					return providerElem.Value as string;
				}
			}
			catch
			{
				return null;
			}
			return null;
		}

19 View Source File : DataConnectionConfiguration.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public void SaveSelectedSource(string source)
		{
			if (!String.IsNullOrEmpty(source))
			{
				try
				{
					XElement xElem = this.RootElement.Element("DataSourceSelection");
					XElement sourceElem = xElem.Element("SelectedSource");
					if (sourceElem != null)
					{
						sourceElem.Value = source;
					}
					else
					{
						xElem.Add(new XElement("SelectedSource", source));
					}
				}
				catch
				{
				}
			}

		}

19 View Source File : DataConnectionConfiguration.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public void SaveSelectedProvider(string provider)
		{
			if (!String.IsNullOrEmpty(provider))
			{
				try
				{
					XElement xElem = this.RootElement.Element("DataSourceSelection");
					XElement sourceElem = xElem.Element("SelectedProvider");
					if (sourceElem != null)
					{
						sourceElem.Value = provider;
					}
					else
					{
						xElem.Add(new XElement("SelectedProvider", provider));
					}
				}
				catch
				{
				}
			}
		}

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 : AzureBlobFileStorage.cs
License : Apache License 2.0
Project Creator : aloneguid

private async Task<IReadOnlyCollection<IOEntry>> ListAsync(
         string path, bool recurse,
         CancellationToken cancellationToken)
      {
         var result = new List<IOEntry>();

         // maxResults default is 5'000

         string prefix = GetPathInContainer(path);

         string rawXml = await ListAsync(GetContainerName(path),
            IOPath.IsRoot(prefix) ? null : (prefix.Trim('/') + "/"),
            delimiter: recurse ? null : "/");

         XElement x = XElement.Parse(rawXml);
         XElement blobs = x.Element("Blobs");
         if(blobs != null)
         {
            result.AddRange(ConvertBatch(blobs));
         }

         XElement nextMarker = x.Element("NextMarker");

         if(recurse)
         {
            Implicits.replacedumeImplicitFolders(path, result);
         }

         return result;
      }

19 View Source File : CrmWorkflowBase.cs
License : MIT License
Project Creator : AndrewButenko

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

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

            var request = XElement.Parse(dictionaryString);

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

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

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

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

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

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

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

            return result;
        }

See More Examples