Esempio n. 1
0
 public override void Clear()
 {
     base.Clear();
     _xmlAttributes = null;
     _xmlChildNodes = null;
     _ownerDocument = null;
 }
Esempio n. 2
0
 public IOSettingsManager(IAppDataManager appDataManager)
 {
     fileName    = appDataManager.RoamingPath + FILE_NAME;
     settings    = new KeyedCollectionFunc <string, IIOSetting>(s => s.Key);
     serializers = new Dictionary <Type, IIOSettingsSerializer>();
     xmlDocument = Load();
 }
Esempio n. 3
0
        private static XmlDocument?SafeLoadXml(string xml)
        {
            XmlDocument?xmlDoc = null;

            try
            {
                using var reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings()
                {
                    XmlResolver = null
                });

                // CA3075 - Unclear message: Unsafe overload of 'LoadXml'
                // see: https://github.com/dotnet/roslyn-analyzers/issues/2477
                xmlDoc = new XmlDocument()
                {
                    XmlResolver = null
                };
                xmlDoc.Load(reader);
            }
            catch (Exception xe)
            {
                xmlDoc = null;
                LogHelper.Error(xe.Message, xe);
            }

            return(xmlDoc);
        }
Esempio n. 4
0
        internal XmlNode?ReadCurrentNode(XmlDocument doc, XmlReader reader)
        {
            _doc    = doc;
            _reader = reader;
            // WS are optional only for loading (see XmlDocument.PreserveWhitespace)
            _preserveWhitespace = true;
            if (doc == null)
            {
                throw new ArgumentException(SR.Xdom_Load_NoDocument);
            }
            if (reader == null)
            {
                throw new ArgumentException(SR.Xdom_Load_NoReader);
            }

            if (reader.ReadState == ReadState.Initial)
            {
                reader.Read();
            }
            if (reader.ReadState == ReadState.Interactive)
            {
                XmlNode n = LoadNode(true) !;

                // Move to the next node
                if (n.NodeType != XmlNodeType.Attribute)
                {
                    reader.Read();
                }

                return(n);
            }

            return(null);
        }
Esempio n. 5
0
        public static bool IsValidXML(this string rawString, out XmlDocument?xmlDoc)
        {
            if (!string.IsNullOrWhiteSpace(rawString))
            {
                rawString = rawString.TrimStart();

                if (rawString.StartsWith("<"))
                {
                    try
                    {
                        var xDoc = XDocument.Parse(rawString);
                        xmlDoc = new XmlDocument();
                        using (var xmlReader = xDoc.CreateReader())
                        {
                            xmlDoc.Load(xmlReader);
                        }
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        xmlDoc = null;
                        Console.WriteLine(ex);
                        return(false);
                    }
                }
            }
            xmlDoc = null;
            return(false);
        }
 public override void Open()
 {
     Document = new XmlDocument();
     if (Exists)
     {
         Document.Load(FileName);
     }
 }
Esempio n. 7
0
    public static string ToXml(this IEnumerable <JObject> item)
    {
        XmlDocument?node = JsonConvert.DeserializeXmlNode(item.ToJson(), nameof(item), true, true);

        string?result = node?.PrettyXml();

        return(result ?? throw new InvalidOperationException());
    }
Esempio n. 8
0
 private static void Init(bool refreshData = false)
 {
     if (FiltersXmlDoc is null || WFPStateXmlDoc is null || refreshData)
     {
         FiltersXmlDoc  = LoadWfpFilters(); // firewall filters
         WFPStateXmlDoc = LoadWfpState();   // all filters added by other provider e.g. firewall apps
     }
 }
Esempio n. 9
0
            internal XmlDocumentResponse(StreamResponse streamResponse, XmlDocument content) : this(streamResponse) {
                if (streamResponse == null)
                {
                    throw new ArgumentNullException(nameof(streamResponse));
                }

                Content = content;
            }
        private void LoadXmlDoc()
        {
            if (!File.Exists(_xmlDocumentationPath))
            {
                return;
            }

            _xmlDoc = new XmlDocument();
            _xmlDoc.Load(_xmlDocumentationPath);
        }
Esempio n. 11
0
        public override IEntry Load(byte[] data)
        {
            _document = new XmlDocument();
            MemoryStream stream = new MemoryStream();

            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            _document.Load(stream);
            return(this);
        }
        /// <summary>
        /// Actually download the maven file.
        /// </summary>
        /// <returns>The path to the downloaded file</returns>
        PackagePhysicalFileMetadata DownloadArtifact(
            MavenPackageID mavenGavFirst,
            string packageId,
            IVersion version,
            Uri feedUri,
            ICredentials feedCredentials,
            string cacheDirectory,
            int maxDownloadAttempts,
            TimeSpan downloadAttemptBackoff,
            XmlDocument?snapshotMetadata)
        {
            Guard.NotNull(mavenGavFirst, "mavenGavFirst can not be null");
            Guard.NotNullOrWhiteSpace(packageId, "packageId can not be null");
            Guard.NotNull(version, "version can not be null");
            Guard.NotNullOrWhiteSpace(cacheDirectory, "cacheDirectory can not be null");
            Guard.NotNull(feedUri, "feedUri can not be null");

            var localDownloadName = Path.Combine(cacheDirectory, PackageName.ToCachedFileName(packageId, version, "." + mavenGavFirst.Packaging));
            var downloadUrl       = feedUri.ToString().TrimEnd('/') +
                                    (snapshotMetadata == null
                    ? mavenGavFirst.DefaultArtifactPath
                    : mavenGavFirst.SnapshotArtifactPath(GetLatestSnapshotRelease(
                                                             snapshotMetadata,
                                                             mavenGavFirst.Packaging,
                                                             mavenGavFirst.Classifier,
                                                             mavenGavFirst.Version)));

            for (var retry = 0; retry < maxDownloadAttempts; ++retry)
            {
                try
                {
                    Log.Verbose($"Downloading Attempt {downloadUrl} TO {localDownloadName}");
                    using (var client = new WebClient
                    {
                        Credentials = feedCredentials
                    })
                    {
                        client.DownloadFile(downloadUrl, localDownloadName);
                        var packagePhysicalFileMetadata = PackagePhysicalFileMetadata.Build(localDownloadName);
                        return(packagePhysicalFileMetadata
                               ?? throw new CommandException($"Unable to retrieve metadata for package {packageId}, version {version}"));
                    }
                }
                catch (Exception ex)
                {
                    if ((retry + 1) == maxDownloadAttempts)
                    {
                        throw new MavenDownloadException("Failed to download the Maven artifact.\r\nLast Exception Message: " + ex.Message);
                    }
                    Thread.Sleep(downloadAttemptBackoff);
                }
            }

            throw new MavenDownloadException("Failed to download the Maven artifact");
        }
Esempio n. 13
0
        internal void ResetParentInElementIdAttrMap(string oldVal, string newVal)
        {
            XmlElement?parentElem = parent as XmlElement;

            Debug.Assert(parentElem != null);
            XmlDocument?doc = parent.OwnerDocument;

            Debug.Assert(doc != null);
            doc.RemoveElementWithId(oldVal, parentElem); //add the element into the hashtable
            doc.AddElementWithId(newVal, parentElem);
        }
Esempio n. 14
0
        private static void Init(bool refreshData = false)
        {
            lock (InitLocker)
            {
                if (FiltersXmlDoc is null || WFPStateXmlDoc is null || refreshData)
                {
                    // Use parallel tasks to speed things up a bit
                    var tFilters = Task.Run(() => FiltersXmlDoc = LoadWfpFilters()); // firewall filters
                    var tStates  = Task.Run(() => WFPStateXmlDoc = LoadWfpState());  // all filters added by other provider e.g. firewall apps

                    Task.WaitAll(tFilters, tStates);
                }
            }
        }
Esempio n. 15
0
        private static XmlDocument?LoadWfpState()
        {
            XmlDocument?xmlDoc      = null;
            var         sys32Folder = Environment.GetFolderPath(Environment.SpecialFolder.System);
            RunResult   rr          = RunCommandCapturing(sys32Folder + @"\netsh.exe", @"wfp show state file=-");

            if (rr.exitCode == 0)
            {
                xmlDoc = SafeLoadXml(rr.outputData.ToString());
            }
            else
            {
                LogHelper.Debug($"netsh error: exitCode={rr.exitCode}\noutput: {rr.outputData.ToString().Substring(1, Math.Min(rr.outputData.Length - 1, 300))}...\nerror: { rr.errorData?.ToString() }");
            }
            return(xmlDoc);
        }
        public bool Apply(XmlDocument xmlTarget)
        {
            if (xmlTarget is null)
            {
                throw new ArgumentNullException(nameof(xmlTarget));
            }

            Debug.Assert(_xmlTarget is null, "This method should not be called recursively");

            if (_xmlTarget is null)
            {
                // Reset the error state
                _logger.HasLoggedErrors = false;

                _xmlTarget        = xmlTarget;
                _xmlTransformable = xmlTarget as XmlTransformableDocument;
                try
                {
                    if (HasTransformNamespace)
                    {
                        InitializeDocumentServices(xmlTarget);

                        TransformLoop(_xmlTransformation);
                    }
                    else
                    {
                        _logger.LogMessage(MessageType.Normal, "The expected namespace {0} was not found in the transform file", TransformNamespace);
                    }
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
                finally
                {
                    ReleaseDocumentServices();

                    _xmlTarget        = null;
                    _xmlTransformable = null;
                }

                return(!_logger.HasLoggedErrors);
            }
            return(false);
        }
Esempio n. 17
0
        internal bool PrepareParentInElementIdAttrMap(string attrPrefix, string attrLocalName)
        {
            XmlElement?parentElem = parent as XmlElement;

            Debug.Assert(parentElem != null);
            XmlDocument?doc = parent.OwnerDocument;

            Debug.Assert(doc != null);
            //The returned attrname if not null is the name with namespaceURI being set to string.Empty
            //Because DTD doesn't support namespaceURI so all comparisons are based on no namespaceURI (string.Empty);
            XmlName?attrname = doc.GetIDInfoByElement(parentElem.XmlName);

            if (attrname != null && attrname.Prefix == attrPrefix && attrname.LocalName == attrLocalName)
            {
                return(true);
            }

            return(false);
        }
Esempio n. 18
0
        private void ParseDocumentType(XmlDocumentType dtNode, bool bUseResolver, XmlResolver?resolver)
        {
            _doc = dtNode.OwnerDocument;
            XmlParserContext  pc = new XmlParserContext(null, new XmlNamespaceManager(_doc !.NameTable), null, null, null, null, _doc.BaseURI, string.Empty, XmlSpace.None);
            XmlTextReaderImpl tr = new XmlTextReaderImpl("", XmlNodeType.Element, pc);

            tr.Namespaces = dtNode.ParseWithNamespaces;
            if (bUseResolver)
            {
                tr.XmlResolver = resolver;
            }

            IDtdParser dtdParser = DtdParser.Create();

            XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(tr);

            IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(_doc.BaseURI, dtNode.Name, dtNode.PublicId, dtNode.SystemId, dtNode.InternalSubset, proxy);

            LoadDocumentType(dtdInfo, dtNode);
        }
Esempio n. 19
0
        internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string innerxmltext, XmlNodeType nt)
        {
            //the function shouldn't be used to set innerxml for XmlDocument node
            Debug.Assert(parentNode.NodeType != XmlNodeType.Document);
            _doc = parentNode.OwnerDocument;
            Debug.Assert(_doc != null);
            XmlParserContext pc = GetContext(parentNode);

            _reader = CreateInnerXmlReader(innerxmltext, nt, pc, _doc);
            try
            {
                _preserveWhitespace = true;
                bool bOrigLoading = _doc.IsLoading;
                _doc.IsLoading = true;

                if (nt == XmlNodeType.Entity)
                {
                    XmlNode?node = null;
                    while (_reader.Read() && (node = LoadNodeDirect()) != null)
                    {
                        parentNode.AppendChildForLoad(node, _doc);
                    }
                }
                else
                {
                    XmlNode?node = null;
                    while (_reader.Read() && (node = LoadNode(true)) != null)
                    {
                        parentNode.AppendChildForLoad(node, _doc);
                    }
                }

                _doc.IsLoading = bOrigLoading;
            }
            finally
            {
                _reader.Close();
            }

            return(pc.NamespaceManager !);
        }
        /// <summary>
        /// Find the first artifact to respond to a HTTP head request. We use this to find the extension
        /// of the artifact that we are trying to download.
        /// </summary>
        /// <returns>The details of the first (and only) artifact to respond to a head request</returns>
        MavenPackageID FirstToRespond(
            MavenPackageID mavenPackageId,
            Uri feedUri,
            ICredentials feedCredentials,
            XmlDocument?snapshotMetadata)
        {
            Guard.NotNull(mavenPackageId, "mavenPackageId can not be null");
            Guard.NotNull(feedUri, "feedUri can not be null");

            var errors     = new ConcurrentBag <string>();
            var fileChecks = JarPackageExtractor.SupportedExtensions
                             .Union(AdditionalExtensions)
                             // Either consider all supported extensions, or select only the specified extension
                             .Where(e => string.IsNullOrEmpty(mavenPackageId.Packaging) || e == "." + mavenPackageId.Packaging)
                             .Select(extension =>
            {
                var packageId = new MavenPackageID(
                    mavenPackageId.Group,
                    mavenPackageId.Artifact,
                    mavenPackageId.Version,
                    Regex.Replace(extension, "^\\.", ""),
                    mavenPackageId.Classifier);
                var result = MavenPackageExists(packageId, feedUri, feedCredentials, snapshotMetadata);
                errors.Add(result.ErrorMsg);
                return(new
                {
                    result.Found,
                    MavenPackageId = packageId
                });
            });

            var firstFound = fileChecks.FirstOrDefault(res => res.Found);

            if (firstFound != null)
            {
                return(firstFound.MavenPackageId);
            }

            throw new MavenDownloadException($"Failed to find the Maven artifact.\r\nReceived Error(s):\r\n{string.Join("\r\n", errors.Distinct().ToList())}");
        }
Esempio n. 21
0
 internal void Export()
 {
     try
     {
         // Remove this if we decide to publish serialization schema at well-known location
         ExportSerializationSchema();
         foreach (KeyValuePair <XmlQualifiedName, DataContract> pair in _dataContractSet)
         {
             DataContract dataContract = pair.Value;
             if (!_dataContractSet.IsContractProcessed(dataContract))
             {
                 ExportDataContract(dataContract);
                 _dataContractSet.SetContractProcessed(dataContract);
             }
         }
     }
     finally
     {
         _xmlDoc          = null;
         _dataContractSet = null !;
     }
 }
Esempio n. 22
0
        /// <summary>
        /// Obtains the XML Element that describes a reflection element by searching the
        /// members for a member that has a name that describes the element.
        /// </summary>
        /// <param name="type">The type or parent type, used to fetch the assembly</param>
        /// <param name="prefix">The prefix as seen in the name attribute in the documentation XML</param>
        /// <param name="name">Where relevant, the full name qualifier for the element</param>
        /// <returns>The member that has a name that describes the specified reflection element</returns>
        private static XmlElement?XmlFromName(this Type?type, char prefix, string name)
        {
            if (type == null)
            {
                return(null);
            }

            string fullName;

            if (string.IsNullOrEmpty(name))
            {
                fullName = prefix + ":" + type.FullName;
            }
            else
            {
                fullName = prefix + ":" + type.FullName + "." + name;
            }

            XmlDocument?xmlDocument = XmlFromAssembly(type.Assembly);

            return(xmlDocument["doc"]["members"].SelectSingleNode("member[@name='" + fullName + "']") as XmlElement);
        }
Esempio n. 23
0
 internal void Load(XmlDocument doc, XmlReader reader, bool preserveWhitespace)
 {
     _doc = doc;
     // perf: unwrap XmlTextReader if no one derived from it
     if (reader.GetType() == typeof(System.Xml.XmlTextReader))
     {
         _reader = ((XmlTextReader)reader).Impl;
     }
     else
     {
         _reader = reader;
     }
     _preserveWhitespace = preserveWhitespace;
     if (doc == null)
     {
         throw new ArgumentException(SR.Xdom_Load_NoDocument);
     }
     if (reader == null)
     {
         throw new ArgumentException(SR.Xdom_Load_NoReader);
     }
     doc.SetBaseURI(reader.BaseURI !);
     if (reader.Settings != null &&
         reader.Settings.ValidationType == ValidationType.Schema)
     {
         doc.Schemas = reader.Settings.Schemas;
     }
     if (_reader.ReadState != ReadState.Interactive)
     {
         if (!_reader.Read())
         {
             return;
         }
     }
     LoadDocSequence(doc);
 }
Esempio n. 24
0
        public XmlDocument CreateCapabilitiesDocument(
            Version version,
            ServiceProperties service,
            IList <Layer> layers,
            IList <string> getMapFormats)
        {
            // TODO: EPSG:4326 support

            var rootNodeName = GetRootNodeName(version);

            doc = new XmlDocument();
            var rootElement = doc.CreateElement(String.Empty, rootNodeName, String.Empty);

            doc.AppendChild(rootElement);

            var versionAttribute = doc.CreateAttribute("version");

            switch (version)
            {
            case Version.Version111: { versionAttribute.Value = Identifiers.Version111; break; }

            case Version.Version130: { versionAttribute.Value = Identifiers.Version130; break; }

            default: throw new ArgumentOutOfRangeException(nameof(version), $"WMS version '{version}' is not supported.");
            }

            rootElement.Attributes.Append(versionAttribute);

            var serviceElement = doc.CreateElement(Identifiers.ServiceElement);

            rootElement.AppendChild(serviceElement);

            var serviceNameElement = doc.CreateElement("Name");

            serviceNameElement.InnerText = "OGC:WMS";
            serviceElement.AppendChild(serviceNameElement);

            var serviceTitleElement = doc.CreateElement("Title");

            serviceTitleElement.InnerText = service.Title ?? String.Empty;
            serviceElement.AppendChild(serviceTitleElement);

            var serviceAbstractElement = doc.CreateElement("Abstract");

            serviceAbstractElement.InnerText = service.Abstract ?? String.Empty;
            serviceElement.AppendChild(serviceAbstractElement);

            var serviceKeywordListElement = doc.CreateElement("KeywordList");

            if (service.Keywords != null)
            {
                foreach (var keyword in service.Keywords)
                {
                    if (!String.IsNullOrWhiteSpace(keyword))
                    {
                        var serviceKeywordElement = doc.CreateElement("Keyword");
                        serviceKeywordElement.InnerText = keyword;
                        serviceKeywordListElement.AppendChild(serviceKeywordElement);
                    }
                }
            }

            serviceElement.AppendChild(serviceKeywordListElement);

            var serviceOnlineResource = CreateOnlineResourceElement(this.baseUrl);

            serviceElement.AppendChild(serviceOnlineResource);

            var capabilityElement = doc.CreateElement(Identifiers.CapabilityElement);

            rootElement.AppendChild(capabilityElement);

            string capabilitiesFormat;

            switch (version)
            {
            case Version.Version111: { capabilitiesFormat = MediaTypeNames.Application.OgcWmsCapabilitiesXml; break; }

            case Version.Version130: { capabilitiesFormat = MediaTypeNames.Text.Xml; break; }

            default: throw new ArgumentOutOfRangeException(nameof(version), $"WMS version '{version}' is not supported.");
            }

            var capabilityRequest = doc.CreateElement("Request");

            capabilityRequest.AppendChild(CreateRequestElement(Identifiers.GetCapabilities, new[] { capabilitiesFormat }));
            capabilityRequest.AppendChild(CreateRequestElement(Identifiers.GetMap, getMapFormats));
            // TODO: ? capabilityRequest.AppendChild(CreateRequestElement(Identifiers.GetFeatureInfo, getFeatureInfoFormats));
            capabilityElement.AppendChild(capabilityRequest);

            var capabilityException       = doc.CreateElement("Exception");
            var capabilityExceptionFormat = doc.CreateElement("Format");

            switch (version)
            {
            case Version.Version111: { capabilityExceptionFormat.InnerText = MediaTypeNames.Application.OgcServiceExceptionXml; break; }

            case Version.Version130: { capabilityExceptionFormat.InnerText = "XML"; break; }

            default: throw new ArgumentOutOfRangeException(nameof(version), $"WMS version '{version}' is not supported.");
            }

            capabilityException.AppendChild(capabilityExceptionFormat);
            capabilityElement.AppendChild(capabilityException);

            foreach (var layer in layers)
            {
                capabilityElement.AppendChild(CreateLayerElement(version, layer));
            }

            return(doc);
        }
Esempio n. 25
0
        private static void ProcessFile(
            ProjectAuthenticationSettings projectAuthenticationSettings,
            string?filePath,
            ConfigurationProperties file)
        {
            if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
            {
                string      fileContent = File.ReadAllText(filePath);
                JsonElement jsonContent = default;
                XmlDocument?xmlDocument = null;

                if (filePath.EndsWith(".json"))
                {
                    jsonContent = JsonSerializer.Deserialize <JsonElement>(fileContent,
                                                                           s_serializerOptionsWithComments);
                }
                else if (filePath.EndsWith(".csproj"))
                {
                    xmlDocument = new XmlDocument();
                    xmlDocument.Load(filePath);
                }

                foreach (PropertyMapping propertyMapping in file.Properties)
                {
                    bool   found    = false;
                    string?property = propertyMapping.Property;
                    if (property != null)
                    {
                        string[] path = property.Split(':');

                        if (filePath.EndsWith(".json"))
                        {
                            IEnumerable <KeyValuePair <JsonElement, int> > elements = FindMatchingElements(jsonContent, path, 0);
                            foreach (var pair in elements)
                            {
                                JsonElement element = pair.Key;
                                int         index   = pair.Value;
                                found = true;
                                string replaceFrom = element.ValueKind == JsonValueKind.Number
                                    ? element.GetInt32().ToString(CultureInfo.InvariantCulture)
                                    : element.ToString() !;

                                UpdatePropertyRepresents(
                                    projectAuthenticationSettings,
                                    filePath,
                                    propertyMapping,
                                    index,
                                    replaceFrom);
                            }
                        }

                        else if (xmlDocument != null)
                        {
                            XmlNode?node = FindMatchingElement(xmlDocument, path);
                            if (node != null)
                            {
                                UpdatePropertyRepresents(
                                    projectAuthenticationSettings,
                                    filePath,
                                    propertyMapping,
                                    0,
                                    node.InnerText);
                            }
                        }
                        else
                        {
                            int index = fileContent.IndexOf(property);
                            if (index != -1)
                            {
                                UpdatePropertyRepresents(
                                    projectAuthenticationSettings,
                                    filePath,
                                    propertyMapping,
                                    0,
                                    property);
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(propertyMapping.Sets) && (found ||
                                                                        (propertyMapping.MatchAny != null && propertyMapping.MatchAny.Any(m => fileContent.Contains(m)))))
                    {
                        projectAuthenticationSettings.ApplicationParameters.Sets(propertyMapping.Sets);
                    }
                }
                // TODO: else AddNotFound?
            }
        }
 public override void Create()
 {
     Document = new XmlDocument();
 }
Esempio n. 27
0
 void IAfterDIContainerBuildListener.AfterDIContainerBuild()
 {
     xmlDocument = null;
 }
        /// <summary>
        /// Most of this yoinked from Brian's SyncSaber.
        /// https://github.com/brian91292/SyncSaber/blob/master/SyncSaber/SyncSaber.cs#L259
        /// </summary>
        /// <param name="pageText"></param>
        /// <exception cref="XmlException"></exception>
        /// <returns></returns>
        public static List <ScrapedSong> ParseXMLPage(string pageText, Uri sourceUri, bool storeRawData)
        {
            if (string.IsNullOrEmpty(pageText))
            {
                return(new List <ScrapedSong>());
            }
            bool        retry       = false;
            var         songsOnPage = new List <ScrapedSong>();
            XmlDocument?xmlDocument = null;

            do
            {
                try
                {
                    xmlDocument = new XmlDocument()
                    {
                        XmlResolver = null
                    };
                    var sr = new StringReader(pageText);
                    using (var reader = XmlReader.Create(sr, new XmlReaderSettings()
                    {
                        XmlResolver = null
                    }))
                    {
                        xmlDocument.Load(reader);
                    }
                    retry = false;
                }
                catch (XmlException ex)
                {
                    if (retry == true)
                    {
                        // TODO: Probably don't need logging here.
                        Logger?.Exception("Exception parsing XML.", ex);
                        throw;
                    }
                    else
                    {
                        Logger?.Debug("Invalid XML formatting detected, attempting to fix...");
                        pageText = pageText.Replace(" & ", " &amp; ");
                        retry    = true;
                    }
                    //File.WriteAllText("ErrorText.xml", pageText);
                }
            } while (retry == true);
            if (xmlDocument == null)
            {
                throw new XmlException($"xmlDocument was null for '{sourceUri}'.");
            }
            XmlNodeList xmlNodeList = xmlDocument.DocumentElement.SelectNodes("/rss/channel/item");

            foreach (object obj in xmlNodeList)
            {
                XmlNode node = (XmlNode)obj;
                if (node["DownloadURL"] == null || node["SongTitle"] == null)
                {
                    Logger?.Debug("Not a song! Skipping!");
                }
                else
                {
                    string?songName    = node[XML_TITLE_KEY].InnerText;
                    string?downloadUrl = node[XML_DOWNLOADURL_KEY]?.InnerText;
                    string?hash        = node[XML_HASH_KEY]?.InnerText?.ToUpper();
                    string?mapperName  = node[XML_AUTHOR_KEY]?.InnerText;
                    string?songKey     = node[XML_SONGKEY_KEY]?.InnerText;
                    if (hash == null || hash.Length == 0) // TODO: Could use Key if Hash was null.
                    {
                        Logger?.Warning($"Skipping BeastSaber song with null hash.");
                        continue;
                    }
                    if (downloadUrl?.Contains("dl.php") ?? true)
                    {
                        Logger?.Warning("Skipping BeastSaber download with old url format!");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(hash))
                        {
                            JObject?jObject = null;
                            if (storeRawData)
                            {
                                jObject = new JObject();
                                jObject.Add(XML_TITLE_KEY, songName);
                                jObject.Add(XML_DOWNLOADURL_KEY, downloadUrl);
                                jObject.Add(XML_HASH_KEY, hash);
                                jObject.Add(XML_AUTHOR_KEY, mapperName);
                                jObject.Add(XML_SONGKEY_KEY, songKey);
                            }

                            songsOnPage.Add(new ScrapedSong(hash, songName, mapperName, Utilities.GetUriFromString(downloadUrl), sourceUri, jObject)
                            {
                                Key = songKey
                            });
                        }
                    }
                }
            }
            return(songsOnPage);
        }
Esempio n. 29
0
 void CloneOriginalDocument() => _xmlOriginal = (XmlDocument)Clone();