Ejemplo n.º 1
0
        public static string RemoveHTMLTags(string content)
        {
            var cleaned = string.Empty;

            try
            {
                StringBuilder textOnly = new StringBuilder();
                using (var reader = XmlNodeReader.Create(new System.IO.StringReader("<xml>" + content + "</xml>")))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Text)
                        {
                            textOnly.Append(reader.ReadContentAsString());
                        }
                    }
                }
                cleaned = textOnly.ToString();
            }
            catch
            {
                //A tag is probably not closed. fallback to regex string clean.
                string textOnly       = string.Empty;
                Regex  tagRemove      = new Regex(@"<[^>]*(>|$)");
                Regex  compressSpaces = new Regex(@"[\s\r\n]+");
                textOnly = tagRemove.Replace(content, string.Empty);
                textOnly = compressSpaces.Replace(textOnly, " ");
                cleaned  = textOnly;
            }

            return(cleaned);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Validates SOAP message from the stream specified.
        /// </summary>
        /// <param name="element"></param>
        /// <returns>True, if stream contains valid messages.</returns>
        public void Validate(XmlElement element)
        {
            XmlReader plainReader = new XmlNodeReader(element);

            while (plainReader.Read())
            {
                ;
            }
            plainReader.Close();
            if (_schemas != null)
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType      = ValidationType.Schema;
                settings.Schemas.XmlResolver = null; //disable resolver - all schemas should be in place

                foreach (XmlSchema schema in _schemas.Schemas)
                {
                    settings.Schemas.Add(schema);
                }
                plainReader = new XmlNodeReader(element);
                XmlReader reader = XmlNodeReader.Create(plainReader, settings);

                while (reader.Read())
                {
                }
            }
        }
        // Extract the styles or stylesWithEffects part from a
        // word processing document as an XDocument instance.
        private XDocument ExtractStylesPart(string fileName, bool getStylesWithEffectsPart)
        {
            XDocument styles = null;

            // Open the document for read access and get a reference.
            using (var document = WordprocessingDocument.Open(fileName, false))
            {
                // Get a reference to the main document part.
                var docPart = document.MainDocumentPart;

                // Assign a reference to the appropriate part to the
                // stylesPart variable.
                StylesPart stylesPart = null;

                if (getStylesWithEffectsPart)
                {
                    stylesPart = docPart.StylesWithEffectsPart;
                }
                else
                {
                    stylesPart = docPart.StyleDefinitionsPart;
                }

                // If the part exists, read it into the XDocument.
                if (stylesPart != null)
                {
                    using (var reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
                    {
                        styles = XDocument.Load(reader);
                    }
                }
            }
            return(styles);
        }
        // Extract the styles or stylesWithEffects part from a document as an XDocument instance.
        public static XDocument WDExtractStyles(
            string fileName,
            bool getStylesWithEffectsPart = true)
        {
            XDocument styles = null;

            using (var document = WordprocessingDocument.Open(fileName, false))
            {
                var docPart = document.MainDocumentPart;

                StylesPart stylesPart = null;
                if (getStylesWithEffectsPart)
                {
                    stylesPart = docPart.StylesWithEffectsPart;
                }
                else
                {
                    stylesPart = docPart.StyleDefinitionsPart;
                }

                if (stylesPart != null)
                {
                    using (var reader = XmlNodeReader.Create(
                               stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
                    {
                        // Create the XDocument:
                        styles = XDocument.Load(reader);
                    }
                }
            }
            return(styles);
        }
Ejemplo n.º 5
0
        private static XDocument GetStylesDoc(string path, bool getStylesWithEffectsPart = false) //выделяем из документа часть, в которой хранятся стили
        {
            XDocument styles = null;

            if (path != null)
            {
                using (var document = WordprocessingDocument.Open(path, false))
                {
                    var docPart = document.MainDocumentPart;

                    StylesPart stylesPart = null;
                    if (getStylesWithEffectsPart)
                    {
                        stylesPart = docPart.StylesWithEffectsPart;
                    }
                    else
                    {
                        stylesPart = docPart.StyleDefinitionsPart;
                    }

                    if (stylesPart != null)
                    {
                        using (var reader = XmlNodeReader.Create(
                                   stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
                        {
                            styles = XDocument.Load(reader);
                        }
                    }
                }
            }
            return(styles);
        }
Ejemplo n.º 6
0
        public async Task Run()
        {
            var cancelToken = _client.CancelToken;

            try
            {
                while (!_client.CancelToken.IsCancellationRequested)
                {
                    foreach (var settings in _settings.AllServers)
                    {
                        foreach (var feed in settings.Value.Feeds)
                        {
                            try {
                                Discord.Channel channel           = _client.GetChannel(feed.Value.ChannelId);
                                DateTimeOffset  newestArticleTime = feed.Value.LastUpdate;
                                XmlReader       r     = XmlNodeReader.Create(feed.Key);
                                SyndicationFeed posts = SyndicationFeed.Load(r);
                                r.Close();
                                foreach (SyndicationItem item in posts.Items)
                                {
                                    if (item.LastUpdatedTime.CompareTo(feed.Value.LastUpdate) > 0)
                                    {
                                        foreach (SyndicationLink link in item.Links) //reddit only has one link. It links to the comments of the post.
                                        {
                                            _client.Log.Info("Feed", $"New article: {item.Title}");
                                            Console.WriteLine(item.Title.Text);
                                            Console.WriteLine("Article written at " + feed.Value.LastUpdate);
                                            Console.WriteLine(link.Uri.OriginalString);
                                            await channel.SendMessage(link.Uri.OriginalString);
                                        }
                                        if (item.LastUpdatedTime.CompareTo(newestArticleTime) > 0)
                                        {
                                            newestArticleTime = item.LastUpdatedTime;
                                        }
                                    }
                                    else
                                    {
                                        // break; Would be fine the Threads were sorted.
                                        // might as well do nothing and be safe.
                                    }
                                }
                                if (feed.Value.LastUpdate.CompareTo(newestArticleTime) != 0)
                                {
                                    feed.Value.LastUpdate = newestArticleTime;
                                    Console.WriteLine("Setting Updatetime to newest Article " + feed.Value.LastUpdate);
                                    await _settings.Save(settings.Key, settings.Value);
                                }
                            }
                            catch (Exception ex) when(!(ex is TaskCanceledException))
                            {
                                _client.Log.Error("Feed", ex);
                            }
                        }
                        await Task.Delay(TIME_BETWEEN_UPDATES, cancelToken);
                    }
                }
            }
            catch (TaskCanceledException) { }
        }
Ejemplo n.º 7
0
        public void XmlNodeReader_SecureSettings()
        {
            var settings = new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Ignore, XmlResolver = new XmlUrlResolver()
            };

            XmlNodeReader.Create("uri", settings).Dispose(); // Compliant
        }
Ejemplo n.º 8
0
        private void SetUnsafeResolverFromMethod()
        {
            var settings = new XmlReaderSettings();

            settings.DtdProcessing = DtdProcessing.Parse;
            settings.XmlResolver   = GetUrlResolver();

            XmlNodeReader.Create("uri", settings).Dispose(); // Noncompliant
        }
Ejemplo n.º 9
0
        public void XmlNodeReader_UnsecureSettings()
        {
            var settings = new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver()
            };

            // Although the XmlNodeReader is safe when using the constructor, the Create method is the one from the base class (XmlReader)
            // and will return an unsecure XmlReader.
            XmlNodeReader.Create("uri", settings).Dispose(); // Noncompliant
        }
Ejemplo n.º 10
0
        private void InsideLambda()
        {
            Func <XmlReaderSettings> settingsFactory = () => new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver()
            };

            var settings = settingsFactory();

            XmlNodeReader.Create("uri", settingsFactory()).Dispose(); // Noncompliant
        }
Ejemplo n.º 11
0
        private void InsideLocalFunction()
        {
            var settings = new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver()
            };

            void LocalFunction()
            {
                XmlNodeReader.Create("uri", settings).Dispose(); // Noncompliant
            }
        }
Ejemplo n.º 12
0
        public void InsideTryCatch()
        {
            var settings = new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver()
            };

            try
            {
                XmlNodeReader.Create("uri", settings).Dispose(); // Noncompliant
            }
            catch
            {
            }
        }
Ejemplo n.º 13
0
        //gavdcodeend 08

        //gavdcodebegin 09
        public static void WordOpenXmlFindStyles()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", false))
            {
                MainDocumentPart docPart    = myWordDoc.MainDocumentPart;
                StylesPart       stylesPart = docPart.StyleDefinitionsPart;

                using (XmlReader reader = XmlNodeReader.Create(
                           stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
                {
                    XDocument docStyles = XDocument.Load(reader);

                    Console.WriteLine(docStyles);
                }
            }
        }
Ejemplo n.º 14
0
        void InitDefaultFontInfo()
        {
            if (WordDocument.MainDocumentPart.StyleDefinitionsPart != null)
            {
                var defaults = WordDocument.MainDocumentPart.StyleDefinitionsPart.Styles.Descendants <DocDefaults>().FirstOrDefault();
                if (defaults.RunPropertiesDefault.RunPropertiesBaseStyle.FontSize != null)
                {
                    DefaultFontSize = Int32.Parse(defaults.RunPropertiesDefault.RunPropertiesBaseStyle.FontSize.Val);
                    if (defaults.RunPropertiesDefault.RunPropertiesBaseStyle.RunFonts.HighAnsi != null)
                    {
                        DefaultFontName = defaults.RunPropertiesDefault.RunPropertiesBaseStyle.RunFonts.HighAnsi;
                    }
                }
            }

            const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            XNamespace   w          = wordmlNamespace;
            StylesPart   stylesPart = WordDocument.MainDocumentPart.StyleDefinitionsPart;

            if (stylesPart != null)
            {
                XDocument styleDoc = null;
                using (var reader = XmlNodeReader.Create(
                           stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
                {
                    // Create the XDocument.
                    styleDoc = XDocument.Load(reader);
                    foreach (var style in styleDoc.Descendants(w + "style"))
                    {
                        var s = new Style(style.ToString());
                        if (s.Default == "1" && s.StyleRunProperties != null)
                        {
                            if (s.StyleRunProperties.FontSize != null)
                            {
                                DefaultFontSize = Int32.Parse(s.StyleRunProperties.FontSize.Val);
                            }
                            if (s.StyleRunProperties.RunFonts != null)
                            {
                                DefaultFontName = s.StyleRunProperties.RunFonts.HighAnsi;
                            }
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 15
0
 public void XmlNodeReader_Default()
 {
     XmlNodeReader.Create("uri").Dispose(); // Compliant
 }
Ejemplo n.º 16
0
        public static List <IBusinessObject> ReadXml(string xml, out string notes, out string notesTable, out string notesField)
        {
            List <IBusinessObject> list        = new List <IBusinessObject>();
            StringBuilder          notesBuffer = new StringBuilder();

            XmlReader reader = XmlNodeReader.Create(new StringReader(xml));

            string          currentElementName = null;
            IBusinessObject currentBO          = null;
            bool            currentBOHasData   = false;
            bool            recordNotes        = false;

            // we have to handle Status, PathTest, QOL_Therapy as special cases, since they have fieldnames = tablenames
            bool insideSpecialTable = false;

            notesTable = null;
            notesField = null;

            Truncator truncator = null;

            while (reader.Read())
            {
                // state machine: every tag hit either forks or saves
                switch (reader.NodeType)
                {
                case XmlNodeType.EndElement:
                    if (insideSpecialTable && reader.Name == currentBO.TableName)
                    {
                        insideSpecialTable = false;
                    }
                    break;

                case XmlNodeType.Element:
                    currentElementName = reader.Name;
                    //if ((!insideSpecialTable && BOFactory.CanBuild(currentElementName)) || currentElementName == "NoTable")
                    if ((!insideSpecialTable && BusinessObjectFactory.CanBuildBusinessObject(currentElementName)) || currentElementName == "NoTable")
                    {
                        if (currentBOHasData)
                        {
                            list.Add(currentBO);

                            if (truncator != null)
                            {
                                truncator.Finish();
                            }
                        }

                        if (currentElementName == "NoTable")
                        {
                            notesTable  = reader.GetAttribute("PutDataInTable");
                            notesField  = reader.GetAttribute("PutDataInField");
                            currentBO   = null;
                            recordNotes = true;
                        }
                        else
                        {
                            //currentBO = BOFactory.GetBO(currentElementName);
                            currentBO   = BusinessObjectFactory.BuildBusinessObject(currentElementName);
                            recordNotes = false;
                            //if (currentBO.HasColumn(currentBO.Tablename))
                            if (currentBO.HasField(currentBO.TableName))
                            {
                                insideSpecialTable = true;
                            }

                            truncator = new Truncator(currentBO);
                        }

                        currentBOHasData = false;
                    }
                    break;

                case XmlNodeType.Text:
                    if (reader.Value != null && reader.Value != "")
                    {
                        // if (recordNotes) // OR !currentBO.HasField(currentElementName)
                        if (recordNotes || !currentBO.HasField(currentElementName))
                        {
                            notesBuffer.Append(" | ");
                            notesBuffer.Append(currentElementName);
                            notesBuffer.Append(" :: ");
                            notesBuffer.Append(reader.Value);
                        }
                        else
                        {
                            currentBO[currentElementName] = truncator.HandleValue(currentElementName, reader.Value);
                            currentBOHasData = true;
                        }
                    }
                    break;
                }
            }

            // finishing up
            if (currentBOHasData)
            {
                list.Add(currentBO);

                if (truncator != null)
                {
                    truncator.Finish();
                }
            }

            reader.Close();

            if (notesBuffer.Length > 0)
            {
                notes = "OTHER EFORM DATA: " + notesBuffer.ToString();
            }
            else
            {
                notes = null;
            }

            return(list);
        }