Here are the examples of the csharp api System.Xml.Linq.XContainer.Add(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
593 Examples
19
View Source File : ProjectWriter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static string GenerateProjectFile(string projFileSource, Example example, string replacedembliesPath)
{
var projXml = XDoreplacedent.Parse(projFileSource);
if (projXml.Root != null)
{
var elements = projXml.Root.Elements().Where(x => x.Name.LocalName == "ItemGroup").ToList();
if (elements.Count == 3)
{
// Add appropriate references
var el = new XElement("Reference", new XAttribute("Include", ExternalDependencies.Replace(".dll", string.Empty)));
el.Add(new XElement("HintPath", Path.Combine(replacedembliesPath, ExternalDependencies)));
elements[0].Add(el);
// Add replacedembly references
foreach (var asmName in replacedembliesNames)
{
el = new XElement("Reference", new XAttribute("Include", asmName.Replace(".dll", string.Empty)));
el.Add(new XElement("HintPath", Path.Combine(replacedembliesPath, asmName)));
elements[0].Add(el);
}
// Add package references for specific example NuGet packages
var examplereplacedle = Regex.Replace(example.replacedle, @"\s", string.Empty);
var examplePackages = NuGetPackages.Where(p => p.StartsWith(examplereplacedle));
if (examplePackages.Any())
{
foreach (var package in examplePackages)
{
// Examplereplacedle;PackageName;PackageVersion
var packageAttr = package.Split(';');
if (packageAttr.Length == 3)
{
el = new XElement("PackageReference",
new XAttribute("Include", packageAttr[1]),
new XAttribute("Version", packageAttr[2]));
elements[1].Add(el);
}
}
}
#if NET452
return projXml.ToString().Replace("[PROJECTTARGET]", "net452");
#else
elements[2].Remove(); // Remove 'net452' references
return projXml.ToString().Replace("[PROJECTTARGET]", "netcoreapp3.1");
#endif
}
}
return projFileSource;
}
19
View Source File : ProjectWriter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static string GenerateShellFile(string shellFileSource, Example example)
{
var sourceFiles = example.SourceFiles;
var view = DirectoryHelper.GetFileNameFromPath(example.Page.Uri);
var xamlFile = sourceFiles.Where(pair => pair.Key.EndsWith(".xaml")).FirstOrDefault(x => x.Key == view);
var ns = GetExampleNamespace(xamlFile.Value, out string fileName);
var xml = XDoreplacedent.Parse(shellFileSource);
if (xml.Root != null)
{
//xmlns
xml.Root.Add(new XAttribute(XNamespace.Xmlns + "example", ClrNamespace + ns));
var userControlElement = new XElement((XNamespace)(ClrNamespace + ns) + fileName);
//ViewModel to Resources
if (example.Page.ViewModel != null)
{
var el = new XElement(PresentationXmlns + "Window.Resources");
el.Add(new XElement((XNamespace)(ClrNamespace + ns) + example.Page.ViewModel.GetType().Name,
new XAttribute(XXmlns + "Key", ViewModelKey)));
xml.Root.Add(el);
//Add DataContext to UserControl is needed
userControlElement.Add(new XAttribute("DataContext", GetStaticResource(ViewModelKey)));
}
xml.Root.Add(userControlElement);
}
return xml.ToString();
}
19
View Source File : GenerateSourceOnlyPackageNuspecsTask.cs
License : MIT License
Project Creator : adamecr
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
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 : ProcessNuPropsTask.cs
License : MIT License
Project Creator : adamecr
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 (SourceFiles == null)
{
Log.LogMessage("No source code available");
return true; //nothing to process
}
//process the source files
var anyPackageAvailable = false;
foreach (var sourceFile in SourceFiles)
{
var fileNameFull = sourceFile.GetMetadata("FullPath");
var fileName = new FileInfo(fileNameFull).Name;
//Get the NuProps from XML Doreplacedentation Comments <NuProp.xxxx>
var sourceContent = File.ReadAllText(fileNameFull);
var sourceLines = sourceContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
//Extract all comments
var stringBuilder = new StringBuilder();
foreach (var contentLine in sourceLines)
{
var sourceLine = contentLine.Trim();
if (sourceLine.StartsWith("///"))
{
stringBuilder.AppendLine(sourceLine.Substring(3));
}
}
//Get all comments in single XML - encapsulate the whole bunch with dummy tag "doc" allowing the XDoreplacedent to parse it
var xDoreplacedent = XDoreplacedent.Parse("<doc>" + stringBuilder + "</doc>");
//Get NuProp comments
var nuPropElements = xDoreplacedent.Descendants()
.Where(n => n is XElement e && e.Name.LocalName.StartsWith("NuProp.")).ToList();
if (nuPropElements.Count <= 0) continue; //no NuProps - continue with the next file
//Has some NuProp -> process
//<NuProp.Id></NuProp.Id> - package ID (mandatory)
//<NuProp.Version></NuProp.Version> - package version base (major.minor.patch) - optional
//<NuProp.Description></NuProp.Description> - package description (optional)
//<NuProp.Tags></NuProp.Tags> - package tags (optional)
//<NuProp.Using id = "" version=""/> - package imports (optional). Version is optional
//<NuProp.Needs id="" /> - "external" imports needed (optional) - not included in package, just info when consuming!!!
var nuPropId = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Id")?.Value.Trim();
var nuPropVersion = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Version")?.Value.Trim();
var nuPropDescription = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Description")?.Value.Trim();
var nuPropTags = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Tags")?.Value.Trim();
var nuPropsIncludes = IncludesEnum.None;
var nuPropIncludesStr = nuPropElements
.FirstOrDefault(e => e.Name.LocalName == "NuProp.Includes" && e.Attribute("type")?.Value != null)?
.Attribute("type")?.Value;
// ReSharper disable once SwitchStatementMissingSomeCases
switch (nuPropIncludesStr)
{
case "Folder": nuPropsIncludes = IncludesEnum.Folder; break;
case "FolderRecursive": nuPropsIncludes = IncludesEnum.FolderRecursive; break;
}
var nuPropUsings = nuPropElements.Where(e => e.Name.LocalName == "NuProp.Using" && e.Attribute("id")?.Value != null).ToList();
if (string.IsNullOrEmpty(nuPropId))
{
Log.LogWarning($"NuProp.Id not found for {fileName}");
continue;
}
//Build the partial NuSpec file
anyPackageAvailable = true;
var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
var outFile = fileNameFull + ".partnuspec";
var outXDoc = File.Exists(outFile) ? XDoreplacedent.Load(outFile) : new XDoreplacedent();
var outXDocStrOriginal = outXDoc.ToString();
var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);
SetOrCreateElement(metadataXElement, "id", ns, nuPropId);
SetOrCreateElement(metadataXElement, "version", ns, nuPropVersion, false); //don't create if the nuPropVersion is empty/not set
SetOrCreateElement(metadataXElement, "description", ns, nuPropDescription, false); //don't create if the nuPropDescription is empty/not set
SetOrCreateElement(metadataXElement, "tags", ns, nuPropTags, false); //don't create if the nuPropTags is empty/not set
GetEmptyOrCreateElement(metadataXElement, "contentFiles", ns)
.Add(new XElement(ns + "files", //<files include="cs/**/*.*" buildAction="Compile" />
new XAttribute("include", "cs/**/*.*"),
new XAttribute("buildAction", "Compile")));
//Dependencies
var dependenciesXElement = GetEmptyOrCreateElement(metadataXElement, "dependencies", ns);
if (nuPropUsings.Count > 0)
{
//have some dependencies
foreach (var nuPropUsing in nuPropUsings)
{
// ReSharper disable once PossibleNullReferenceException - should not be null based on Where clause for nuPropUsings
var depId = nuPropUsing.Attribute("id").Value;
var depVersion = nuPropUsing.Attribute("version")?.Value;
var dependencyXElement = new XElement(ns + "dependency", new XAttribute("id", depId), new XAttribute("include", "all"));
if (string.IsNullOrEmpty(depVersion)) depVersion = "%%CURRENT_VERSION%%";
dependencyXElement.Add(new XAttribute("version", depVersion));
dependenciesXElement.Add(dependencyXElement);
}
}
else
{
//Clean dependencies
dependenciesXElement.Remove();
}
//<files>
// < file src = "src.cs" target = "content\App_Packages\pkg_id\src.cs" />
// < file src = "src.cs" target = "contentFiles\cs\any\App_Packages\pkg_id\src.cs" />
//</ files >
var files = GetEmptyOrCreateElement(packageXElement, "files", ns);
files.Add(
new XElement(ns + "file", new XAttribute("src", fileName),
new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{fileName}")),
new XElement(ns + "file", new XAttribute("src", fileName),
new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{fileName}")));
if (nuPropsIncludes != IncludesEnum.None)
{
var mainItemDir = sourceFile.GetMetadata("RootDir") + sourceFile.GetMetadata("Directory");
Log.LogMessage($"MainItemDir:{mainItemDir}");
IEnumerable<ITaskItem> itemsToAdd;
switch (nuPropsIncludes)
{
case IncludesEnum.Folder:
itemsToAdd = SourceFiles.Where(itm =>
itm.GetMetadata("RootDir") + itm.GetMetadata("Directory") == mainItemDir &&
itm.GetMetadata("FullPath") != fileNameFull);
break;
case IncludesEnum.FolderRecursive:
itemsToAdd = SourceFiles.Where(itm =>
(itm.GetMetadata("RootDir") + itm.GetMetadata("Directory")).StartsWith(mainItemDir) &&
itm.GetMetadata("FullPath") != fileNameFull);
break;
default:
throw new ArgumentOutOfRangeException();
}
foreach (var item in itemsToAdd)
{
var itemFileFull = item.GetMetadata("FullPath");
Log.LogMessage($"itemFileFull:{itemFileFull}");
var itemFileRel = itemFileFull.Substring(mainItemDir.Length);
files.Add(
new XElement(ns + "file", new XAttribute("src", itemFileRel),
new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{itemFileRel}")),
new XElement(ns + "file", new XAttribute("src", itemFileRel),
new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{itemFileRel}")));
}
}
var outXDocStrNew = outXDoc.ToString();
if (outXDocStrNew == outXDocStrOriginal) continue;
//change - > save
File.WriteAllText(outFile, outXDocStrNew);
Log.LogMessage($"Generated/updated {outFile}");
}
if (!anyPackageAvailable)
{
Log.LogMessage("No source-only packages found");
}
return true;
}
19
View Source File : SetVersionInfoTask.cs
License : MIT License
Project Creator : adamecr
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 : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlFilterCondition(this XContainer filter, string attribute, string operatorName, string value)
{
if (filter == null)
{
throw new ArgumentNullException("filter");
}
var condition = new XElement("condition");
condition.SetAttributeValue("attribute", attribute);
condition.SetAttributeValue("operator", operatorName);
condition.SetAttributeValue("value", value);
filter.Add(condition);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlFilterInCondition(this XContainer filter, string attribute, IEnumerable<string> values)
{
if (filter == null)
{
throw new ArgumentNullException("filter");
}
if (!values.Any())
{
throw new ArgumentException("Value can't be null or empty.", "values");
}
var valueArray = values as string[] ?? values.ToArray();
var condition = new XElement("condition");
condition.SetAttributeValue("attribute", attribute);
condition.SetAttributeValue("operator", "in");
foreach (var value in valueArray)
{
var valueElement = new XElement("value");
valueElement.SetValue(value);
condition.Add(valueElement);
}
filter.Add(condition);
}
19
View Source File : WebsiteIdeaUserAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IEnumerable<IIdeaIdeaVotePair> SelectIdeaVotes(int startRowIndex = 0, int maximumRows = -1)
{
if (startRowIndex < 0)
{
throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
}
if (maximumRows == 0)
{
return new IIdeaIdeaVotePair[] { };
}
if (startRowIndex % maximumRows != 0)
{
throw new ArgumentException("maximumRows must be a factor of startRowIndex");
}
var serviceContext = Dependencies.GetServiceContext();
var security = Dependencies.GetSecurityProvider();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""feedback"">
<all-attributes />
<order attribute=""createdon"" descending=""false"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
<condition attribute=""rating"" operator=""not-null"" />
</filter>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
var filter = enreplacedy.Descendants("filter").First();
filter.AddFetchXmlFilterCondition("adx_voterid", "eq", UserId.ToString());
enreplacedy.AddFetchXmlLinkEnreplacedy("adx_idea", "adx_ideaid", "regardingobjectid",
addCondition => addCondition("statecode", "eq", "0"),
addNestedLinkEnreplacedy => addNestedLinkEnreplacedy("adx_ideaforum", "adx_ideaforumid", "adx_ideaforumid",
addCondition =>
{
addCondition("adx_websiteid", "eq", Website.Id.ToString());
addCondition("statecode", "eq", "0");
}));
var linkEnreplacedy = enreplacedy.Descendants("link-enreplacedy").First();
linkEnreplacedy.SetAttributeValue("alias", "idea");
linkEnreplacedy.Add(new XElement("all-attributes"));
IEnumerable<Enreplacedy> enreplacedies;
if (maximumRows < 0)
{
var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.ToString())
});
enreplacedies = response.EnreplacedyCollection.Enreplacedies.Where(e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read)).ToArray();
}
else
{
var paginator = new FetchXmlPostFilterPaginator(serviceContext, fetchXml, e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read), 2);
enreplacedies = paginator.Select(startRowIndex, maximumRows).ToArray();
}
var ideas = CreateIdeaEnreplacediesFromAliasedValues(enreplacedies);
return new IdeaIdeaVotePairFactory(serviceContext, Dependencies.GetHttpContext(), Dependencies.GetPortalUser()).Create(ideas, enreplacedies);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlFilterCondition(this XContainer filter, string attribute, string operatorName, string value)
{
filter.ThrowOnNull("filter");
var condition = new XElement("condition");
condition.SetAttributeValue("attribute", attribute);
condition.SetAttributeValue("operator", operatorName);
condition.SetAttributeValue("value", value);
filter.Add(condition);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlFilterCondition(this XContainer filter, string attribute, string operatorName)
{
filter.ThrowOnNull("filter");
var condition = new XElement("condition");
condition.SetAttributeValue("attribute", attribute);
condition.SetAttributeValue("operator", operatorName);
filter.Add(condition);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlLinkEnreplacedy(this XContainer enreplacedy, string linkEnreplacedyLogicalName, string linkFromAttributeLogicalName, string linkToAttributeLogicalName, Action<Action<string, string, string>> addFilterConditions, Action<Action<string, string, string, Action<Action<string, string, string>>>> addNestedLinkEnreplacedies = null)
{
enreplacedy.ThrowOnNull("enreplacedy");
var linkEnreplacedy = new XElement("link-enreplacedy");
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var filter = new XElement("filter");
filter.SetAttributeValue("type", "and");
addFilterConditions(filter.AddFetchXmlFilterCondition);
if (addNestedLinkEnreplacedies != null)
{
addNestedLinkEnreplacedies(linkEnreplacedy.AddFetchXmlLinkEnreplacedy);
}
linkEnreplacedy.Add(filter);
enreplacedy.Add(linkEnreplacedy);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlLinkEnreplacedy(this XContainer enreplacedy, string linkEnreplacedyLogicalName, string linkFromAttributeLogicalName, string linkToAttributeLogicalName, Action<Action<string, string, string>> addFilterConditions)
{
enreplacedy.ThrowOnNull("enreplacedy");
var linkEnreplacedy = new XElement("link-enreplacedy");
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var filter = new XElement("filter");
filter.SetAttributeValue("type", "and");
addFilterConditions(filter.AddFetchXmlFilterCondition);
linkEnreplacedy.Add(filter);
enreplacedy.Add(linkEnreplacedy);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlFilterCondition(this XContainer filter, string attribute, string operatorName,
string value)
{
filter.ThrowOnNull("filter");
var condition = new XElement("condition");
condition.SetAttributeValue("attribute", attribute);
condition.SetAttributeValue("operator", operatorName);
condition.SetAttributeValue("value", value);
filter.Add(condition);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlLinkEnreplacedy(
this XContainer enreplacedy,
string linkEnreplacedyLogicalName,
string linkFromAttributeLogicalName,
string linkToAttributeLogicalName,
Action<Action<string, string, string>> addFilterConditions,
Action<Action<string, string, string, Action<Action<string, string, string>>>> addNestedLinkEnreplacedies = null)
{
enreplacedy.ThrowOnNull("enreplacedy");
var linkEnreplacedy = new XElement("link-enreplacedy");
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var filter = new XElement("filter");
filter.SetAttributeValue("type", "and");
addFilterConditions(filter.AddFetchXmlFilterCondition);
if (addNestedLinkEnreplacedies != null)
{
addNestedLinkEnreplacedies(linkEnreplacedy.AddFetchXmlLinkEnreplacedy);
}
linkEnreplacedy.Add(filter);
enreplacedy.Add(linkEnreplacedy);
}
19
View Source File : XContainerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void AddFetchXmlLinkEnreplacedy(
this XContainer enreplacedy,
string linkEnreplacedyLogicalName,
string linkFromAttributeLogicalName,
string linkToAttributeLogicalName,
Action<Action<string, string, string>> addFilterConditions)
{
enreplacedy.ThrowOnNull("enreplacedy");
var linkEnreplacedy = new XElement("link-enreplacedy");
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var filter = new XElement("filter");
filter.SetAttributeValue("type", "and");
addFilterConditions(filter.AddFetchXmlFilterCondition);
linkEnreplacedy.Add(filter);
enreplacedy.Add(linkEnreplacedy);
}
19
View Source File : CrmEntityIndexerExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static FetchXml GetFetchXmlFilteredToSingleEnreplacedy(this ICrmEnreplacedyIndexer indexer, string fetchXml, OrganizationServiceContext dataContext, string enreplacedyLogicalName, Guid id)
{
var filteredFetchXml = XDoreplacedent.Parse(fetchXml);
var enreplacedy = filteredFetchXml.XPathSelectElements("/fetch/enreplacedy")
.Where(e => e.Attributes("name").Any(a => a.Value == enreplacedyLogicalName))
.FirstOrDefault();
if (enreplacedy == null)
{
throw new InvalidOperationException("Invalid FetchXML, unable to find enreplacedy element in FetchXML:\n\n{0}".FormatWith(filteredFetchXml));
}
var existingFilter = enreplacedy.XPathSelectElement("filter");
var idFilter = new XElement("filter");
idFilter.Add(new XAttribute("type", "and"));
var condition = new XElement("condition");
var primaryKey = GetPrimaryKeyField(indexer, dataContext, enreplacedyLogicalName);
condition.Add(new XAttribute("attribute", primaryKey));
condition.Add(new XAttribute("operator", "eq"));
condition.Add(new XAttribute("value", id.ToString()));
idFilter.Add(condition);
if (existingFilter != null)
{
existingFilter.Remove();
idFilter.Add(existingFilter);
}
enreplacedy.Add(idFilter);
return new FetchXml(filteredFetchXml);
}
19
View Source File : FetchXml.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public void AddConditionalStatement(string type, string attributeLogicalName, string op, string value = null, string linkEnreplacedyAlias = null)
{
var filter = new XElement("filter");
filter.SetAttributeValue("type", type);
var condition = new XElement("condition");
condition.SetAttributeValue("attribute", attributeLogicalName);
condition.SetAttributeValue("operator", op);
if (value != null)
{
condition.SetAttributeValue("value", value);
}
filter.Add(condition);
if (linkEnreplacedyAlias == null)
{
foreach (var element in _xml.XPathSelectElements("//fetch/enreplacedy"))
{
element.Add(filter);
}
}
else
{
var enreplacedy = _xml
.XPathSelectElements("//fetch/enreplacedy")
.FirstOrDefault(e => e.Attributes("name").Any(a => a.Value == LogicalName));
if (enreplacedy == null)
{
return;
}
var linkEnreplacedy = enreplacedy
.XPathSelectElements("link-enreplacedy")
.FirstOrDefault(e => e.Attributes("alias").Any(a => a.Value == linkEnreplacedyAlias));
if (linkEnreplacedy == null)
{
return;
}
linkEnreplacedy.Add(filter);
}
}
19
View Source File : FetchXml.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void AddFetchElement(XElement fetchElement)
{
foreach (var element in _xml.XPathSelectElements("//fetch/enreplacedy"))
{
element.Add(fetchElement);
}
}
19
View Source File : FetchXml.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public void AddLinkEnreplacedyAttribute(string alias, string attributeLogicalName)
{
var enreplacedy = _xml
.XPathSelectElements("//fetch/enreplacedy")
.FirstOrDefault(e => e.Attributes("name").Any(a => a.Value == LogicalName));
if (enreplacedy == null)
{
return;
}
var linkEnreplacedy = enreplacedy
.XPathSelectElements("link-enreplacedy")
.FirstOrDefault(e => e.Attributes("alias").Any(a => a.Value == alias));
if (linkEnreplacedy == null)
{
return;
}
linkEnreplacedy.Add(new XElement("attribute", new XAttribute("name", attributeLogicalName)));
}
19
View Source File : FetchXmlResultsFilter.cs
License : MIT License
Project Creator : Adoxio
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 : FetchXmlResultsFilter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void InsertRelatedFields(Dictionary<string, XElement> listOfNodes, RelatedField relatedField)
{
foreach (var relationship in relatedField.ListOfFields)
{
if (relationship.Value.Split(',').Length <= 1)
{
continue;
}
var relatedEnreplacediesIds = relationship.Value.Split(',');
var node = listOfNodes[relationship.Key];
var field = node.Descendants(relatedField.FieldName).FirstOrDefault();
if (field != null)
{
field.Remove();
}
foreach (var id in relatedEnreplacediesIds)
{
node.Add(new XElement(relatedField.FieldName, id));
}
listOfNodes[relationship.Key] = node;
}
}
19
View Source File : WebsiteIdeaUserAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IEnumerable<IIdeaIdeaCommentPair> SelectIdeaComments(int startRowIndex = 0, int maximumRows = -1)
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return new IdeaIdeaCommentPair[] { };
}
if (startRowIndex < 0)
{
throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
}
if (maximumRows == 0)
{
return new IIdeaIdeaCommentPair[] { };
}
if (startRowIndex % maximumRows != 0)
{
throw new ArgumentException("maximumRows must be a factor of startRowIndex");
}
var serviceContext = Dependencies.GetServiceContext();
var security = Dependencies.GetSecurityProvider();
XDoreplacedent fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""feedback"">
<all-attributes />
<order attribute=""adx_date"" descending=""false"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
</filter>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
var filter = enreplacedy.Descendants("filter").First();
filter.AddFetchXmlFilterCondition("adx_authorid", "eq", UserId.ToString());
enreplacedy.AddFetchXmlLinkEnreplacedy("adx_idea", "adx_ideaid", "regardingobjectid",
addCondition => addCondition("statecode", "eq", "0"),
addNestedLinkEnreplacedy => addNestedLinkEnreplacedy("adx_ideaforum", "adx_ideaforumid", "adx_ideaforumid",
addCondition =>
{
addCondition("adx_websiteid", "eq", Website.Id.ToString());
addCondition("statecode", "eq", "0");
}));
var linkEnreplacedy = enreplacedy.Descendants("link-enreplacedy").First();
linkEnreplacedy.SetAttributeValue("alias", "idea");
linkEnreplacedy.Add(new XElement("all-attributes"));
IEnumerable<Enreplacedy> enreplacedies;
if (maximumRows < 0)
{
var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.ToString())
});
enreplacedies = response.EnreplacedyCollection.Enreplacedies.Where(e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read)).ToArray();
}
else
{
var paginator = new FetchXmlPostFilterPaginator(serviceContext, fetchXml, e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read), 2);
enreplacedies = paginator.Select(startRowIndex, maximumRows).ToArray();
}
var ideas = CreateIdeaEnreplacediesFromAliasedValues(enreplacedies);
return new IdeaIdeaCommentPairFactory(serviceContext, Dependencies.GetHttpContext(), Dependencies.GetPortalUser()).Create(ideas, enreplacedies);
}
19
View Source File : FetchXml.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public void AddAttribute(string attributeLogicalName)
{
foreach (var element in _xml.XPathSelectElements("//fetch/enreplacedy"))
{
element.Add(new XElement("attribute", new XAttribute("name", attributeLogicalName)));
}
}
19
View Source File : FetchXml.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public void AddLinkEnreplacedy(string name, string fromAttribute, string toAttribute, string alias, string type,
bool visible = false, bool intersect = false)
{
foreach (var element in _xml.XPathSelectElements("//fetch/enreplacedy"))
{
var link = new XElement("link-enreplacedy");
link.SetAttributeValue("name", name);
link.SetAttributeValue("from", fromAttribute);
link.SetAttributeValue("to", toAttribute);
link.SetAttributeValue("alias", alias);
link.SetAttributeValue("link-type", type);
link.SetAttributeValue("visible", visible);
link.SetAttributeValue("intersect", intersect);
element.Add(link);
}
}
19
View Source File : SubjectControlTemplate.cs
License : MIT License
Project Creator : Adoxio
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
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 : CrmDataSourceView.cs
License : MIT License
Project Creator : Adoxio
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 : XmlNodeConverter.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public override IXmlNode AppendChild(IXmlNode newChild)
{
Container.Add(newChild.WrappedNode);
_childNodes = null;
return newChild;
}
19
View Source File : XmlNodeConverter.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public void SetAttributeNode(IXmlNode attribute)
{
XObjectWrapper wrapper = (XObjectWrapper)attribute;
Element.Add(wrapper.WrappedNode);
_attributes = null;
}
19
View Source File : UpdateChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
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
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
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 : CourtSystem.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
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
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
License : GNU General Public License v3.0
Project Creator : Albo1125
private static void HandleNewButtonAdding(string Plugin, string ButtonName, string XMLFile)
{
GameFiber.StartNew(delegate
{
while (!currentNewButtonPopup.hasDisplayed && !string.IsNullOrWhiteSpace(currentNewButtonPopup.Popupreplacedle))
{
newButtonsInQueue = true;
GameFiber.Sleep(10);
if (ButtonName != lastButtonName)
{
GameFiber.Sleep(100);
}
}
lastButtonName = ButtonName;
newButtonsInQueue = false;
currentNewButtonPopup = new Popup("PoliceSmartRadio Setup: New Button (" + ButtonName + ")",
Plugin + " is adding a new button, " + ButtonName + ", to " + Path.GetFileName(XMLFile) + ". Would you like to enable it in " + Path.GetFileName(XMLFile) + "? You can change this at any time by editing the XML file manually.",
newButtonAnswers, false, true);
currentNewButtonPopup.Display();
while (currentNewButtonPopup.IndexOfGivenAnswer == -1)
{
GameFiber.Yield();
}
XDoreplacedent xdoc = XDoreplacedent.Load(XMLFile);
xdoc.Root.Add(new XElement("Button", new XElement("Plugin", Plugin), new XElement("Name", ButtonName), new XElement("Enabled", (currentNewButtonPopup.IndexOfGivenAnswer == 0).ToString())));
xdoc.Save(XMLFile);
if (!newButtonsInQueue)
{
Game.DisplayNotification("This was the last new button in the queue. LSPDFR will now reload so ~b~PoliceSmartRadio~s~ can refresh itself. Type 'forceduty' in console once it's done.");
GameFiber.Sleep(3000);
Game.ReloadActivePlugin();
}
});
}
19
View Source File : SmartSystemMenuSettings.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static void Save(string fileName, SmartSystemMenuSettings settings)
{
var doreplacedent = new XDoreplacedent();
doreplacedent.Add(new XElement("smartSystemMenu",
new XElement("processExclusions", settings.ProcessExclusions.Select(x => new XElement("processName", x))),
new XElement("menuItems",
new XElement("items", settings.MenuItems.Items.Select(x => new XElement("item",
new XAttribute("type", x.Type.ToString()),
x.Type == MenuItemType.Item || x.Type == MenuItemType.Group ? new XAttribute("name", x.Name) : null,
x.Show == false ? new XAttribute("show", x.Show.ToString().ToLower()) : null,
x.Type == MenuItemType.Item ? new XAttribute("key1", x.Key1 == VirtualKeyModifier.None ? "" : ((int)x.Key1).ToString()) : null,
x.Type == MenuItemType.Item ? new XAttribute("key2", x.Key2 == VirtualKeyModifier.None ? "" : ((int)x.Key2).ToString()) : null,
x.Type == MenuItemType.Item ? new XAttribute("key3", x.Key3 == VirtualKey.None ? "" : ((int)x.Key3).ToString()) : null,
x.Items.Any() ?
new XElement("items", x.Items.Select(y => new XElement("item",
new XAttribute("type", y.Type.ToString()),
y.Type == MenuItemType.Item || y.Type == MenuItemType.Group ? new XAttribute("name", y.Name) : null,
y.Show == false ? new XAttribute("show", y.Show.ToString().ToLower()) : null,
y.Type == MenuItemType.Item ? new XAttribute("key1", y.Key1 == VirtualKeyModifier.None ? "" : ((int)y.Key1).ToString()) : null,
y.Type == MenuItemType.Item ? new XAttribute("key2", y.Key2 == VirtualKeyModifier.None ? "" : ((int)y.Key2).ToString()) : null,
y.Type == MenuItemType.Item ? new XAttribute("key3", y.Key3 == VirtualKey.None ? "" : ((int)y.Key3).ToString()) : null))) : null))),
new XElement("windowSizeItems", settings.MenuItems.WindowSizeItems.Select(x => new XElement("item",
new XAttribute("replacedle", x.replacedle),
new XAttribute("left", x.Left == null ? "" : x.Left.Value.ToString()),
new XAttribute("top", x.Top == null ? "" : x.Top.Value.ToString()),
new XAttribute("width", x.Width),
new XAttribute("height", x.Height),
new XAttribute("key1", x.Key1 == VirtualKeyModifier.None ? "" : ((int)x.Key1).ToString()),
new XAttribute("key2", x.Key2 == VirtualKeyModifier.None ? "" : ((int)x.Key2).ToString()),
new XAttribute("key3", x.Key3 == VirtualKey.None ? "" : ((int)x.Key3).ToString())))),
new XElement("startProgramItems", settings.MenuItems.StartProgramItems.Select(x => new XElement("item",
new XAttribute("replacedle", x.replacedle),
new XAttribute("fileName", x.FileName),
new XAttribute("arguments", x.Arguments))))),
new XElement("closer",
new XAttribute("type", ((int)settings.Closer.Type).ToString()),
new XAttribute("key1", settings.Closer.Key1 == VirtualKeyModifier.None ? "" : ((int)settings.Closer.Key1).ToString()),
new XAttribute("key2", settings.Closer.Key2 == VirtualKeyModifier.None ? "" : ((int)settings.Closer.Key2).ToString()),
new XAttribute("mouseButton", settings.Closer.MouseButton == MouseButton.None ? "" : ((int)settings.Closer.MouseButton).ToString())
),
new XElement("sizer",
new XAttribute("type", ((int)settings.Sizer).ToString())
),
new XElement("systemTrayIcon",
new XAttribute("show", settings.ShowSystemTrayIcon.ToString().ToLower())
),
new XElement("language",
new XAttribute("name", settings.LanguageName.ToLower())
)));
Save(fileName, doreplacedent);
}
19
View Source File : DataConnectionConfiguration.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
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 : DataConnectionConfiguration.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
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 : CrmWorkflowBase.cs
License : MIT License
Project Creator : AndrewButenko
License : MIT License
Project Creator : AndrewButenko
public string SerializeDictionary(Dictionary<string, object> dictionary)
{
var rootElement = new XElement("Request");
foreach (var key in dictionary.Keys)
{
var childElement = new XElement(key);
var value = dictionary[key];
if (value == null)
{
var isnullAttribute = new XAttribute("IsNull", true);
childElement.Add(isnullAttribute);
}
else
{
var typeName = value.GetType().ToString();
var typeAttribute = new XAttribute("Type", typeName);
childElement.Add(typeAttribute);
switch (typeName)
{
case "System.Boolean":
case "System.String":
case "System.Int32":
case "System.DateTime":
case "System.Decimal":
childElement.SetValue(value);
break;
case "Microsoft.Xrm.Sdk.OptionSetValue":
childElement.SetValue(((OptionSetValue)value).Value);
break;
case "Microsoft.Xrm.Sdk.Money":
childElement.SetValue(((Money)value).Value);
break;
case "Microsoft.Xrm.Sdk.EnreplacedyReference":
var enreplacedyReference = (EnreplacedyReference)value;
childElement.Add(new XElement("Id", enreplacedyReference.Id));
childElement.Add(new XElement("LogicalName", enreplacedyReference.LogicalName));
break;
default:
throw new InvalidPluginExecutionException($"Serialization is not implemented for {typeName} clreplaced");
}
}
rootElement.Add(childElement);
}
return rootElement.ToString();
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetConditionalActionSetSaveElement(SerializableConditionalActionSet set)
{
var result = GetConditionSaveElement(set.Condition);
for (var i = 0; i < set.Actions.Count; i++)
result.Add(GetActionSaveElement(set.Actions[i]));
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetConditionalActionsSaveElement(RunnableConditionalActions actions)
{
var result = new XElement("ConditionalActions");
foreach (var action in actions.Actions)
{
result.Add(GetConditionalActionSetSaveElement(action));
}
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetDLCSaveElement(OS os)
{
var result = new XElement("DLC");
result.SetAttributeValue("Active", os.IsInDLCMode.ToString());
result.SetAttributeValue("LoadedContent", os.HasLoadedDLCContent.ToString());
var DLCFlags = new XElement("Flags");
DLCFlags.SetAttributeValue("OriginalFaction", os.PreDLCFaction);
result.Add(DLCFlags);
var OriginalNodes = new XElement("OriginalVisibleNodes");
OriginalNodes.SetValue(os.PreDLCVisibleNodesCache);
result.Add(OriginalNodes);
result.Add(GetConditionalActionsSaveElement(os.ConditionalActions));
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetMemoryContentsSaveElement(MemoryContents contents)
{
var result = new XElement("Memory");
if (contents.DataBlocks != null && contents.DataBlocks.Count > 0)
{
var dataTag = new XElement("Data");
foreach (var dataBlock in contents.DataBlocks)
{
var blockTag = new XElement("Block");
blockTag.SetValue(dataBlock);
dataTag.Add(blockTag);
}
result.Add(dataTag);
}
if (contents.CommandsRun != null && contents.CommandsRun.Count > 0)
{
var dataTag = new XElement("Commands");
foreach (var command in contents.CommandsRun)
{
var blockTag = new XElement("Command");
blockTag.SetValue(command);
dataTag.Add(blockTag);
}
result.Add(dataTag);
}
if (contents.FileFragments != null && contents.FileFragments.Count > 0)
{
var dataTag = new XElement("FileFragments");
foreach (var fileFrag in contents.FileFragments)
{
var blockTag = new XElement("File");
blockTag.SetAttributeValue("name", fileFrag.Key);
blockTag.SetValue(fileFrag.Value);
dataTag.Add(blockTag);
}
result.Add(dataTag);
}
if (contents.Images != null && contents.Images.Count > 0)
{
var dataTag = new XElement("Images");
foreach (var image in contents.Images)
{
var blockTag = new XElement("Image");
blockTag.SetValue(image);
dataTag.Add(blockTag);
}
result.Add(dataTag);
}
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetFolderSaveElement(Folder folder)
{
var result = new XElement("folder");
result.SetAttributeValue("name", folder.name);
foreach (var internalFolder in folder.folders)
result.Add(GetFolderSaveElement(internalFolder));
foreach (var file in folder.files)
{
var fileTag = new XElement("file");
fileTag.SetAttributeValue("name", file.name);
fileTag.SetValue(file.data);
result.Add(fileTag);
}
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetFilesystemSaveElement(FileSystem fs)
{
var result = new XElement("filesystem");
result.Add(GetFolderSaveElement(fs.root));
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetNodeSaveElement(Computer node)
{
var result = new XElement("computer");
result.SetAttributeValue("name", node.name);
result.SetAttributeValue("ip", node.ip);
result.SetAttributeValue("type", node.type);
var spec = "none";
if (node.os.netMap.mailServer.Equals(node))
{
spec = "mail";
}
if (node.os.thisComputer.Equals(node))
{
spec = "player";
}
result.SetAttributeValue("spec", spec);
result.SetAttributeValue("id", node.idName);
if (node.icon != null)
{
result.SetAttributeValue("icon", node.icon);
}
if (node.attatchedDeviceIDs != null)
{
result.SetAttributeValue("devices", node.attatchedDeviceIDs);
}
if (node.HasTracker)
{
result.SetAttributeValue("tracker", "true");
}
var locationTag = new XElement("location");
locationTag.SetAttributeValue("x", node.location.X.ToString(CultureInfo.InvariantCulture));
locationTag.SetAttributeValue("y", node.location.Y.ToString(CultureInfo.InvariantCulture));
result.Add(locationTag);
var securityTag = new XElement("security");
securityTag.SetAttributeValue("level", node.securityLevel);
securityTag.SetAttributeValue("traceTime", node.traceTime.ToString(CultureInfo.InvariantCulture));
if (node.startingOverloadTicks > 0f)
{
securityTag.SetAttributeValue("proxyTime", (node.hasProxy ? node.startingOverloadTicks.ToString(CultureInfo.InvariantCulture) : "-1"));
}
securityTag.SetAttributeValue("adminIP", node.adminIP);
securityTag.SetAttributeValue("portsToCrack", node.portsNeededForCrack);
result.Add(securityTag);
result.Add(GetPortSaveElement(node));
var adminTag = new XElement("admin");
string adminType;
switch (node.admin)
{
case null:
adminType = "none";
break;
case BaseAdministrator pfAdmin:
adminTag = XMLStorageAttribute.WriteToElement(pfAdmin);
adminType = node.admin.GetType().Name;
break;
case FastBasicAdministrator _:
adminType = "fast";
break;
case FastProgressOnlyAdministrator _:
adminType = "progress";
break;
case BasicAdministrator _:
adminType = "basic";
break;
default:
adminType = node.admin.GetType().Name;
break;
}
adminTag.SetAttributeValue("type", adminType);
adminTag.SetAttributeValue("resetPreplaced", node.admin?.ResetsPreplacedword ?? false);
adminTag.SetAttributeValue("isSuper", node.admin?.IsSuper ?? false);
result.Add(adminTag);
var linksTag = new XElement("links");
var links = new StringBuilder();
foreach (var link in node.links)
links.Append(" " + link);
linksTag.SetValue(links.ToString());
result.Add(linksTag);
if (node.firewall != null)
result.Add(GetFirewallSaveElement(node.firewall));
var usersTag = new XElement("users");
foreach (var detail in node.users)
usersTag.Add(GetUserDetailSaveElement(detail));
result.Add(usersTag);
if (node.Memory != null)
result.Add(GetMemoryContentsSaveElement(node.Memory));
var daemonsTag = new XElement("daemons");
daemonsTag.Add(node.daemons.Select(GetDaemonSaveElement).ToArray());
result.Add(daemonsTag);
result.Add(GetFilesystemSaveElement(node.files));
var eventResult = EventManager<SaveComputerEvent>.InvokeAll(new SaveComputerEvent(node.os, node, result));
return eventResult.Cancelled ? null : eventResult.Element;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetNetmapSaveElement(NetworkMap nmap)
{
var result = new XElement("NetworkMap");
result.SetAttributeValue("sort", nmap.SortingAlgorithm);
result.Add(GetNetmapVisibleNodesSaveElement(nmap));
result.Add(GetNetmapNodesSaveElement(nmap));
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetMissionSaveElement(ActiveMission mission)
{
var result = new XElement("mission");
if (mission == null) {
result.SetAttributeValue("next", "NULL_MISSION");
result.SetAttributeValue("goals", "none");
result.SetAttributeValue("activeCheck", "none");
return result;
}
result.SetAttributeValue("next", mission.nextMission);
result.SetAttributeValue("goals", mission.reloadGoalsSourceFile);
result.SetAttributeValue("reqRank", mission.requiredRank);
if (mission.wasAutoGenerated)
{
result.SetAttributeValue("genTarget", mission.genTarget);
result.SetAttributeValue("genFile", mission.genFile);
result.SetAttributeValue("genPath", mission.genPath);
result.SetAttributeValue("genTargetName", mission.genTargetName);
result.SetAttributeValue("genOther", mission.genOther);
}
result.SetAttributeValue("activeCheck", mission.activeCheck);
var email = new XElement("email");
email.SetAttributeValue("sender", mission.email.sender);
email.SetAttributeValue("subject", mission.email.subject);
email.SetValue(mission.email.body);
result.Add(email);
var endFunctionVal = new XElement("endFunc");
endFunctionVal.SetAttributeValue("val", mission.endFunctionValue);
endFunctionVal.SetAttributeValue("name", mission.endFunctionName);
result.Add(endFunctionVal);
var postingTag = new XElement("posting");
postingTag.SetAttributeValue("replacedle", mission.postingreplacedle);
postingTag.SetValue(mission.postingBody);
result.Add(postingTag);
return result;
}
19
View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist
License : MIT License
Project Creator : Arkhist
internal static XElement GetFactionSaveElement(Faction faction)
{
var tagName = "Faction";
switch (faction)
{
case EntropyFaction _:
tagName = "EntropyFaction";
break;
case HubFaction _:
tagName = "HubFaction";
break;
case CustomFaction _:
tagName = "CustomFaction";
break;
}
var result = new XElement(tagName);
result.SetAttributeValue("name", faction.name);
result.SetAttributeValue("id", faction.idName);
result.SetAttributeValue("neededVal", faction.neededValue);
result.SetAttributeValue("playerVal", faction.playerValue);
result.SetAttributeValue("playerHasPreplaceded", faction.playerHasPreplacededValue);
if (faction is CustomFaction customFaction)
{
foreach (var action in customFaction.CustomActions)
{
var actionElement = new XElement("Action");
actionElement.SetAttributeValue("ValueRequired", action.ValueRequiredForTrigger);
if (action.FlagsRequiredForTrigger != null)
{
actionElement.SetAttributeValue("Flags", action.FlagsRequiredForTrigger);
}
actionElement.Add(action.TriggerActions.Select(GetActionSaveElement).ToArray());
result.Add(actionElement);
}
}
return result;
}
See More Examples