Пример #1
0
        public void ReadXML(XmlReader reader)
        {
            reader.ReadStartElement();

            while (reader.NodeType == XmlNodeType.Element)
            {
                switch (reader.Name)
                {
                case "CapturePathConfiguration":
                    capturePathConfiguration.ReadXml(reader);
                    break;

                case "DisplaySynchronizationFramerate":
                    string str = reader.ReadElementContentAsString();
                    displaySynchronizationFramerate = double.Parse(str, CultureInfo.InvariantCulture);
                    break;

                case "CaptureRecordingMode":
                    recordingMode = (CaptureRecordingMode)Enum.Parse(typeof(CaptureRecordingMode), reader.ReadElementContentAsString());
                    break;

                case "SaveUncompressedVideo":
                    saveUncompressedVideo = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                case "VerboseStats":
                    verboseStats = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                case "MemoryBuffer":
                    memoryBuffer = reader.ReadElementContentAsInt();
                    break;

                case "Cameras":
                    ParseCameras(reader);
                    break;

                case "DelayCompositeConfiguration":
                    delayCompositeConfiguration.ReadXml(reader);
                    break;

                case "PhotofinishConfiguration":
                    photofinishConfiguration.ReadXml(reader);
                    break;

                case "CaptureAutomationConfiguration":
                    captureAutomationConfiguration.ReadXml(reader);
                    break;

                case "HighspeedRecordingFramerateThreshold":
                    string hrft = reader.ReadElementContentAsString();
                    highspeedRecordingFramerateThreshold = float.Parse(hrft, CultureInfo.InvariantCulture);
                    break;

                case "HighspeedRecordingFramerateOutput":
                    string hrfo = reader.ReadElementContentAsString();
                    highspeedRecordingFramerateOutput = float.Parse(hrfo, CultureInfo.InvariantCulture);
                    break;

                case "SlowspeedRecordingFramerateThreshold":
                    string srft = reader.ReadElementContentAsString();
                    slowspeedRecordingFramerateThreshold = float.Parse(srft, CultureInfo.InvariantCulture);
                    break;

                case "SlowspeedRecordingFramerateOutput":
                    string srfo = reader.ReadElementContentAsString();
                    slowspeedRecordingFramerateOutput = float.Parse(srfo, CultureInfo.InvariantCulture);
                    break;

                case "PostRecordCommand":
                    postRecordCommand = reader.ReadElementContentAsString();
                    break;

                case "CaptureKVA":
                    captureKVA = reader.ReadElementContentAsString();
                    break;

                default:
                    reader.ReadOuterXml();
                    break;
                }
            }

            reader.ReadEndElement();
        }
Пример #2
0
        public void ReadXML(XmlReader reader)
        {
            reader.ReadStartElement();

            while (reader.NodeType == XmlNodeType.Element)
            {
                switch (reader.Name)
                {
                case "TimecodeFormat":
                    timecodeFormat = (TimecodeFormat)Enum.Parse(typeof(TimecodeFormat), reader.ReadElementContentAsString());
                    break;

                case "SpeedUnit":
                    speedUnit = (SpeedUnit)Enum.Parse(typeof(SpeedUnit), reader.ReadElementContentAsString());
                    break;

                case "AccelerationUnit":
                    accelerationUnit = (AccelerationUnit)Enum.Parse(typeof(AccelerationUnit), reader.ReadElementContentAsString());
                    break;

                case "AngleUnit":
                    angleUnit = (AngleUnit)Enum.Parse(typeof(AngleUnit), reader.ReadElementContentAsString());
                    break;

                case "AngularVelocityUnit":
                    angularVelocityUnit = (AngularVelocityUnit)Enum.Parse(typeof(AngularVelocityUnit), reader.ReadElementContentAsString());
                    break;

                case "AngularAccelerationUnit":
                    angularAccelerationUnit = (AngularAccelerationUnit)Enum.Parse(typeof(AngularAccelerationUnit), reader.ReadElementContentAsString());
                    break;

                case "CustomLengthUnit":
                    customLengthUnit = reader.ReadElementContentAsString();
                    break;

                case "CustomLengthAbbreviation":
                    customLengthAbbreviation = reader.ReadElementContentAsString();
                    break;

                case "AspectRatio":
                    aspectRatio = (ImageAspectRatio)Enum.Parse(typeof(ImageAspectRatio), reader.ReadElementContentAsString());
                    break;

                case "DeinterlaceByDefault":
                    deinterlaceByDefault = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                case "InteractiveFrameTracker":
                    interactiveFrameTracker = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                case "WorkingZoneSeconds":
                    workingZoneSeconds = reader.ReadElementContentAsInt();
                    break;

                case "WorkingZoneMemory":
                    workingZoneMemory = reader.ReadElementContentAsInt();
                    break;

                case "SyncLockSpeed":
                    syncLockSpeed = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                case "ImageFormat":
                    imageFormat = (KinoveaImageFormat)Enum.Parse(typeof(KinoveaImageFormat), reader.ReadElementContentAsString());
                    break;

                case "VideoFormat":
                    videoFormat = (KinoveaVideoFormat)Enum.Parse(typeof(KinoveaVideoFormat), reader.ReadElementContentAsString());
                    break;

                case "InfoFading":
                    defaultFading.ReadXml(reader);
                    break;

                case "MaxFading":
                    maxFading = reader.ReadElementContentAsInt();
                    break;

                case "DrawOnPlay":
                    drawOnPlay = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                case "RecentColors":
                    ParseRecentColors(reader);
                    break;

                case "MaxRecentColors":
                    maxRecentColors = reader.ReadElementContentAsInt();
                    break;

                case "TrackingProfile":
                    trackingProfile.ReadXml(reader);
                    break;

                case "EnableFiltering":
                    enableFiltering = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                case "EnableCustomToolsDebugMode":
                    enableCustomToolsDebugMode = XmlHelper.ParseBoolean(reader.ReadElementContentAsString());
                    break;

                default:
                    reader.ReadOuterXml();
                    break;
                }
            }

            reader.ReadEndElement();
        }
        /// <summary>
        /// Attempts to read the <see cref="XmlSignatureConstants.Elements.X509Data"/> element conforming to https://www.w3.org/TR/2001/PR-xmldsig-core-20010820/#sec-X509Data.
        /// </summary>
        /// <param name="reader">A <see cref="XmlReader"/> positioned on a <see cref="XmlSignatureConstants.Elements.X509Data"/> element.</param>
        /// <param name="data">The parsed <see cref="XmlSignatureConstants.Elements.X509Data"/> element.</param>
        protected virtual bool TryReadX509Data(XmlReader reader, out X509Data data)
        {
            if (reader == null)
            {
                throw LogArgumentNullException(nameof(reader));
            }

            if (!reader.IsStartElement(XmlSignatureConstants.Elements.X509Data, XmlSignatureConstants.Namespace))
            {
                data = null;
                return(false);
            }

            data = new X509Data();

            if (reader.IsEmptyElement)
            {
                throw XmlUtil.LogReadException(GetLogMessage("IDX30108"));
            }

            reader.ReadStartElement(XmlSignatureConstants.Elements.X509Data, XmlSignatureConstants.Namespace);
            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(XmlSignatureConstants.Elements.X509Certificate, XmlSignatureConstants.Namespace))
                {
                    data.Certificates.Add(reader.ReadElementContentAsString());
                }
                else if (reader.IsStartElement(XmlSignatureConstants.Elements.X509IssuerSerial, XmlSignatureConstants.Namespace))
                {
                    if (data.IssuerSerial != null)
                    {
                        throw XmlUtil.LogReadException(GetLogMessage("IDX30015"), XmlSignatureConstants.Elements.X509IssuerSerial);
                    }
                    data.IssuerSerial = ReadIssuerSerial(reader);
                }
                else if (reader.IsStartElement(XmlSignatureConstants.Elements.X509SKI, XmlSignatureConstants.Namespace))
                {
                    if (data.SKI != null)
                    {
                        throw XmlUtil.LogReadException(GetLogMessage("IDX30015"), XmlSignatureConstants.Elements.X509SKI);
                    }
                    data.SKI = reader.ReadElementContentAsString();
                }
                else if (reader.IsStartElement(XmlSignatureConstants.Elements.X509SubjectName, XmlSignatureConstants.Namespace))
                {
                    if (data.SubjectName != null)
                    {
                        throw XmlUtil.LogReadException(GetLogMessage("IDX30015"), XmlSignatureConstants.Elements.X509SubjectName);
                    }
                    data.SubjectName = reader.ReadElementContentAsString();
                }
                else if (reader.IsStartElement(XmlSignatureConstants.Elements.X509CRL, XmlSignatureConstants.Namespace))
                {
                    if (data.CRL != null)
                    {
                        throw XmlUtil.LogReadException(GetLogMessage("IDX30015"), XmlSignatureConstants.Elements.X509CRL);
                    }
                    data.CRL = reader.ReadElementContentAsString();
                }
                else
                {
                    // Skip the element since it is not one of  <X509Certificate>, <X509IssuerSerial>, <X509SKI>, <X509SubjectName>, <X509CRL>
                    LogHelper.LogWarning(GetLogMessage("IDX30300"), reader.ReadOuterXml());
                }
            }

            // </X509Data>
            reader.ReadEndElement();

            return(true);
        }
Пример #4
0
        private static void ConvertPostLink(SiteUris uris, XmlReader r, SequentialTurtleWriter w, UnknownValueStore <string> unknownLinkTypeIds)
        {
            if (r.MoveToAttribute("LinkTypeId"))
            {
                switch (r.Value)
                {
                case "1":                         // linked
                    if (r.MoveToAttribute("PostId"))
                    {
                        w.StartTriple(uris.CreatePostUri(r.Value));
                        if (r.MoveToAttribute("RelatedPostId"))
                        {
                            w.AddToTriple(uris.GeneralUris.LinkProperty, uris.CreatePostUri(r.Value));
                        }
                    }
                    break;

                case "3":                         // duplicate
                    if (r.MoveToAttribute("RelatedPostId"))
                    {
                        w.StartTriple(uris.CreatePostUri(r.Value));
                        if (r.MoveToAttribute("PostId"))
                        {
                            w.AddToTriple(uris.GeneralUris.DuplicateProperty, uris.CreatePostUri(r.Value));
                        }
                    }
                    break;

                default:
                    unknownLinkTypeIds.RegisterUnknownValue(r.Value);
                    break;
                }
            }
            else
            {
                r.MoveToElement();
                ConsoleHelper.WriteErrorLine("No LinkTypeId attribute found on element {0}. Skipping element.", r.ReadOuterXml());
            }
        }
        internal static PSSessionConfigurationData Create(string configurationData)
        {
            PSSessionConfigurationData configuration = new PSSessionConfigurationData();

            if (string.IsNullOrEmpty(configurationData))
            {
                return(configuration);
            }

            configurationData = Unescape(configurationData);

            XmlReaderSettings readerSettings = new XmlReaderSettings
            {
                CheckCharacters = false,
                IgnoreComments  = true,
                IgnoreProcessingInstructions = true,
                MaxCharactersInDocument      = 10000,
                XmlResolver      = null,
                ConformanceLevel = ConformanceLevel.Fragment
            };

            using (XmlReader reader = XmlReader.Create(new StringReader(configurationData), readerSettings))
            {
                // read the header <SessionConfigurationData>
                if (reader.ReadToFollowing(SessionConfigToken))
                {
                    bool isParamFound = reader.ReadToDescendant(ParamToken);
                    while (isParamFound)
                    {
                        if (!reader.MoveToAttribute(NameToken))
                        {
                            throw PSTraceSource.NewArgumentException(configurationData,
                                                                     RemotingErrorIdStrings.NoAttributesFoundForParamElement,
                                                                     NameToken, ValueToken, ParamToken);
                        }

                        string optionName = reader.Value;

                        if (string.Equals(optionName, PrivateDataToken, StringComparison.OrdinalIgnoreCase))
                        {
                            // this is a PrivateData element which we
                            // need to process
                            if (reader.ReadToFollowing(PrivateDataToken))
                            {
                                string privateData = reader.ReadOuterXml();

                                AssertValueNotAssigned(PrivateDataToken, configuration._privateData);
                                configuration._privateData = privateData;
                            }
                        }
                        else
                        {
                            if (!reader.MoveToAttribute(ValueToken))
                            {
                                throw PSTraceSource.NewArgumentException(configurationData,
                                                                         RemotingErrorIdStrings.NoAttributesFoundForParamElement,
                                                                         NameToken, ValueToken, ParamToken);
                            }

                            string optionValue = reader.Value;
                            configuration.Update(optionName, optionValue);
                        }

                        // move to next Param token.
                        isParamFound = reader.ReadToFollowing(ParamToken);
                    }
                }
            }

            configuration.CreateCollectionIfNecessary();

            return(configuration);
        }
Пример #6
0
        private bool ReadItem(XmlReader r)
        {
            string title       = "";
            string link        = "";
            string description = "";

            r.Read();
            r.Read();
            while (!r.EOF)
            {
                if ((r.Name == "item") && (!r.IsStartElement()))
                {
                    break;
                }
                if (r.Name == "title")
                {
                    title = r.ReadElementContentAsString();
                }
                else if (r.Name == "description")
                {
                    description = r.ReadElementContentAsString();
                }
                else if ((r.Name == "link") && (string.IsNullOrEmpty(link)))
                {
                    link = r.ReadElementContentAsString();
                }
                else if ((r.Name == "enclosure") && (r.GetAttribute("type") == "application/x-bittorrent"))
                {
                    link = r.GetAttribute("url");
                    r.ReadOuterXml();
                }
                else
                {
                    r.ReadOuterXml();
                }
            }
            if ((string.IsNullOrEmpty(title)) || (string.IsNullOrEmpty(link)))
            {
                return(false);
            }

            string showName = "";

            TVDoc.FindSeasEp("", title, out int season, out int episode, out int maxEp, null, this.regxps);

            try
            {
                Match m = Regex.Match(description, "Show Name: (.*?)[;|$]", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    showName = m.Groups[1].ToString();
                }
                m = Regex.Match(description, "Season: ([0-9]+)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    season = int.Parse(m.Groups[1].ToString());
                }
                m = Regex.Match(description, "Episode: ([0-9]+)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    episode = int.Parse(m.Groups[1].ToString());
                }
            }
            catch
            {
                // ignored
            }

            if ((season != -1) && (episode != -1))
            {
                Add(new RSSItem(link, title, season, episode, showName));
            }

            return(true);
        }
Пример #7
0
 /// <summary></summary>
 public override string ReadOuterXml()
 {
     Console.WriteLine("ReadOuterXml");
     return(_internal.ReadOuterXml());
 }
Пример #8
0
        public List <Dictionary <string, object> > ReadFromDataTableXML(string s)//从生成的数据表里面恢复数据
        {
            List <Dictionary <string, object> > rs = new List <Dictionary <string, object> >();

            StringReader xs     = new StringReader(s);
            XmlReader    reader = XmlReader.Create(xs);

            if (!reader.ReadToFollowing("DataTable"))
            {
                return(null);
            }                                                         //找到该类的标签,如果没有,那么没法加载,返回空
            //如果找到了该类的标签,那么就到该类的第一个元素

            bool IsNotEnd = reader.Read();

            while (IsNotEnd)//进入当前的对象进行读取,主要是子标签
            {
                switch (reader.NodeType)
                {
                case XmlNodeType.Element:

                    string tag = reader.Name;
                    if (tag == "DataRow")
                    {
                        string ss = reader.ReadOuterXml();
                        Dictionary <string, object> td = ReadFromDataRowXML(ss);
                        if (td == null)
                        {
                        }
                        else
                        {
                            rs.Add(td);
                        }
                    }
                    break;

                case XmlNodeType.Text:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.XmlDeclaration:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.ProcessingInstruction:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.Comment:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.Attribute:
                    reader.Read();
                    break;

                case XmlNodeType.Whitespace:
                    reader.Read();
                    break;

                case XmlNodeType.EndElement:
                    IsNotEnd = false;
                    break;
                }
            }
            return(rs);
        }
Пример #9
0
 /// <summary>See <see cref="XmlReader.ReadOuterXml"/>.</summary>
 public override string ReadOuterXml()
 {
     return(_reader.ReadOuterXml());
 }
Пример #10
0
        public Episode(XmlReader r)
        {
            // <Episode>
            //  <id>...</id>
            //  blah blah
            // </Episode>

            try
            {
                SetDefaults(null, null, null);

                r.Read();
                if (r.Name != "Episode")
                {
                    return;
                }

                r.Read();
                while (!r.EOF)
                {
                    if ((r.Name == "Episode") && (!r.IsStartElement()))
                    {
                        break;
                    }

                    if (r.Name == "id")
                    {
                        EpisodeId = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "seriesid")
                    {
                        SeriesId = r.ReadElementContentAsInt(); // thetvdb series id
                    }
                    else if (r.Name == "seasonid")
                    {
                        SeasonId = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "EpisodeNumber")
                    {
                        AiredEpNum = r.ReadElementContentAsInt();
                    }
                    else if (r.Name == "dvdEpisodeNumber")
                    {
                        string den = r.ReadElementContentAsString();
                        int.TryParse(den, out DvdEpNum);
                    }
                    else if (r.Name == "SeasonNumber")
                    {
                        string sn = r.ReadElementContentAsString();
                        int.TryParse(sn, out ReadAiredSeasonNum);
                    }
                    else if (r.Name == "dvdSeason")
                    {
                        string dsn = r.ReadElementContentAsString();
                        int.TryParse(dsn, out ReadDvdSeasonNum);
                    }
                    else if (r.Name == "lastupdated")
                    {
                        SrvLastUpdated = r.ReadElementContentAsLong();
                    }
                    else if (r.Name == "Overview")
                    {
                        Overview = System.Web.HttpUtility.HtmlDecode(XmlHelper.ReadStringFixQuotesAndSpaces(r));
                    }
                    else if (r.Name == "Rating")
                    {
                        EpisodeRating = XmlHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "GuestStars")
                    {
                        EpisodeGuestStars = XmlHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "EpisodeDirector")
                    {
                        EpisodeDirector = XmlHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "Writer")
                    {
                        Writer = XmlHelper.ReadStringFixQuotesAndSpaces(r);
                    }
                    else if (r.Name == "EpisodeName")
                    {
                        Name = System.Web.HttpUtility.HtmlDecode(XmlHelper.ReadStringFixQuotesAndSpaces(r));
                    }
                    else if (r.Name == "FirstAired")
                    {
                        try
                        {
                            string contents = r.ReadElementContentAsString();
                            if (contents == "")
                            {
                                Logger.Info("Please confirm, but we are assuming that " + Name + "(episode Id =" +
                                            EpisodeId + ") has no airdate");

                                FirstAired = null;
                            }
                            else
                            {
                                FirstAired = DateTime.ParseExact(contents, "yyyy-MM-dd",
                                                                 new System.Globalization.CultureInfo(""));
                            }
                        }
                        catch
                        {
                            FirstAired = null;
                        }
                    }
                    else
                    {
                        if ((r.IsEmptyElement) || !r.IsStartElement())
                        {
                            r.ReadOuterXml();
                        }
                        else
                        {
                            XmlReader r2 = r.ReadSubtree();
                            r2.Read();
                            string name = r2.Name;
                            items[name] = r2.ReadElementContentAsString();
                            r.Read();
                        }
                    }
                }
            }
            catch (XmlException e)
            {
                string message = "Error processing data from TheTVDB for an episode.";
                if (SeriesId != -1)
                {
                    message += "\r\nSeries ID: " + SeriesId;
                }

                if (EpisodeId != -1)
                {
                    message += "\r\nEpisode ID: " + EpisodeId;
                }

                if (DvdEpNum != -1)
                {
                    message += "\r\nEpisode (DVD) Number: " + DvdEpNum;
                }

                if (AiredEpNum != -1)
                {
                    message += "\r\nEpisode Aired Number: " + AiredEpNum;
                }

                if (!string.IsNullOrEmpty(Name))
                {
                    message += "\r\nName: " + Name;
                }

                Logger.Error(e, message);

                throw new TheTVDB.TVDBException(e.Message);
            }
        }
Пример #11
0
        /// <summary>
        /// Fix any errors you can, and write the results out.  If successful, the input
        /// file is renamed with a ".bak" extension, the output file is renamed to the
        /// original input filename, and a log file with a ".fixes" extension is written.
        /// </summary>
        public void FixErrorsAndSave()
        {
            m_progress.Maximum  = m_crt;
            m_progress.Position = 0;
            m_progress.Message  = String.Format(Strings.ksLookingForAndFixingErrors, m_filename);
            string            infile            = m_filename;
            string            outfile           = m_filename + "-x";
            var               filesToDelete     = new List <string>();  // remember intermediate files so they can be deleted.
            var               currentErrorCount = 0;
            XmlWriterSettings settings          = new XmlWriterSettings {
                Indent = true, IndentChars = String.Empty
            };

            // 20 is not a magic number, but it's comfortably larger than any iteration we expect (maximum ownership chain depth + 1).
            // and some limit is desired to keep bugs in our fixup code from iterating forever
            for (int repeatCount = 0; repeatCount < 20; ++repeatCount)
            {
                outfile = m_filename + "-x" + repeatCount;
                if (repeatCount > 0)
                {
                    InitializeFixers(infile);
                    filesToDelete.Add(infile);
                }
                using (XmlWriter xw = XmlWriter.Create(outfile, settings))
                {
                    xw.WriteStartDocument();

                    using (XmlReader xrdr = XmlReader.Create(infile))
                    {
                        xrdr.MoveToContent();
                        if (xrdr.Name != "languageproject")
                        {
                            throw new Exception(String.Format("Unexpected outer element (expected <Lists>): {0}", xrdr.Name));
                        }
                        xw.WriteStartElement("languageproject");
                        xw.WriteAttributes(xrdr, false);
                        xrdr.Read();
                        xrdr.MoveToContent();
                        if (xrdr.Name == "AdditionalFields")
                        {
                            string sXml = xrdr.ReadOuterXml();
                            var    xe   = XElement.Parse(sXml);
                            xe.WriteTo(xw);
                            xrdr.MoveToContent();
                        }
                        while (xrdr.Name == "rt")
                        {
                            var rtXml = xrdr.ReadOuterXml();
                            var rt    = XElement.Parse(rtXml);
                            // set flag to false if we don't want to write out this rt element, i.e. delete it!
                            // N.B.: Any deleting of owned objects requires two passes, so that the reference
                            // to the object being deleted can be cleaned up too!
                            var guid = rt.Attribute("guid").Value;
                            if (!m_rtElementsToDelete.Contains(guid))
                            {
                                var fwrite = true;
                                foreach (var fixer in m_rtLevelFixers)
                                {
                                    if (!fixer.FixElement(rt, errorLogger))
                                    {
                                        fwrite = false;
                                    }
                                }
                                if (fwrite)
                                {
                                    rt.WriteTo(xw);
                                }
                            }
                            else
                            {
                                var className    = rt.Attribute("class").Value;
                                var errorMessage = String.Format(Strings.ksUnusedRtElement, className, guid);
                                errorLogger(errorMessage, true);
                            }
                            xrdr.MoveToContent();
                            m_progress.Step(1);
                        }
                        xrdr.Close();
                    }
                    xw.WriteEndDocument();
                    xw.Close();
                }
                var newErrorCount = errorCounter();
                if (newErrorCount == currentErrorCount)
                {
                    break;                      // If no errors were fixed on this pass, we can quit.
                }
                currentErrorCount = newErrorCount;
                infile            = outfile;
            }
            var bakfile = Path.ChangeExtension(m_filename, LcmFileHelper.ksFwDataFallbackFileExtension);

            if (File.Exists(bakfile))
            {
                File.Delete(bakfile);
            }
            File.Move(m_filename, bakfile);
            File.Move(outfile, m_filename);
            foreach (var file in filesToDelete)
            {
                File.Delete(file);
            }
        }
Пример #12
0
        public void ReadLineXml(XmlReader r, PointF scaling)
        {
            r.ReadStartElement();
            float    length = 0;
            SegmentF line   = SegmentF.Empty;

            calibrationAxis = CalibrationAxis.LineHorizontal;

            while (r.NodeType == XmlNodeType.Element)
            {
                switch (r.Name)
                {
                case "Length":
                    length = float.Parse(r.ReadElementContentAsString(), CultureInfo.InvariantCulture);
                    break;

                case "Segment":
                    line = ParseSegment(r, scaling);
                    break;

                case "Origin":
                    // Import from older format.
                    origin = XmlHelper.ParsePointF(r.ReadElementContentAsString());
                    if (float.IsNaN(origin.X) || float.IsNaN(origin.Y))
                    {
                        origin = PointF.Empty;
                    }

                    origin = origin.Scale(scaling.X, scaling.Y);
                    break;

                case "Axis":
                    calibrationAxis = (CalibrationAxis)Enum.Parse(typeof(CalibrationAxis), r.ReadElementContentAsString());
                    break;

                case "Scale":
                    // Import and convert from older format.
                    // Create a fake line of 100 px horizontal at the origin.
                    float  bakedScale   = float.Parse(r.ReadElementContentAsString(), CultureInfo.InvariantCulture);
                    float  lengthPixels = 100;
                    PointF start        = origin;
                    PointF end          = origin.Translate(lengthPixels, 0);
                    line   = new SegmentF(start, end);
                    length = lengthPixels * bakedScale;

                    // The actual origin should be expressed in the calibrated plane coordinate system, which has its true origin at the A point of the quad.
                    origin = new PointF(0, length);
                    break;

                default:
                    string unparsed = r.ReadOuterXml();
                    log.DebugFormat("Unparsed content in KVA XML: {0}", unparsed);
                    break;
                }
            }

            r.ReadEndElement();

            // Update mapping.
            size      = new SizeF(length, length);
            quadImage = MakeQuad(line.Start, line.End, calibrationAxis);

            mapping.Update(new QuadrilateralF(size.Width, size.Height), quadImage);
            valid       = quadImage.IsConvex;
            initialized = true;
        }
 public virtual void ReadXml(XmlReader reader)
 {
     Data = reader.ReadOuterXml();
 }
Пример #14
0
 // Get an XML text string from an XmlReader
 internal static string GetXmlFromXmlReader(XmlReader xmlReader)
 {
     return(xmlReader != null ? xmlReader.ReadOuterXml() : null);
 }
 public override string ReadOuterXml()
 {
     CheckAsync();
     return(_coreReader.ReadOuterXml());
 }
Пример #16
0
    private void CreateElementsForTileMap(XmlReader tilemap)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(tilemap.ReadOuterXml());

        XmlNode imageNode = doc.ChildNodes[0];

        float scaleInverse = Futile.resourceScaleInverse;

        //XMLNode imageNode = tilemap.children[0] as XMLNode;
        string sourceString = imageNode.Attributes["name"].Value.ToString();

        tileWidth = Convert.ToInt32(imageNode.Attributes["tilewidth"].Value.ToString());
        tileHeight = Convert.ToInt32(imageNode.Attributes["tileheight"].Value.ToString());

        int firstGID = Convert.ToInt32(imageNode.Attributes["firstgid"].Value.ToString());

        imageNode = imageNode.ChildNodes[0];
        int sourceWidth = Convert.ToInt32(imageNode.Attributes["width"].Value.ToString());
        int sourceHeight = Convert.ToInt32(imageNode.Attributes["height"].Value.ToString());

        int numRows = (sourceHeight / tileHeight);
        int numCols = (sourceWidth / tileWidth);
        int totalTiles = numRows * numCols;

        // load tileset image
        Futile.atlasManager.LoadImage("Atlases/" + sourceString);
        FAtlasElement origElement = Futile.atlasManager.GetElementWithName("Atlases/" + sourceString);

        Vector2 _textureSize = origElement.atlas.textureSize;

        int gid = firstGID;
        for(int i = 0; i < totalTiles; i++) {

            FAtlasElement element = new FAtlasElement();

            string name = "tile_" + gid;

            element.name = name;

            element.isTrimmed = origElement.isTrimmed;

            element.atlas = origElement.atlas;
            element.atlasIndex = i;

            //the uv coordinate rectangle within the atlas
            float frameX = (origElement.uvRect.x * _textureSize.x) - origElement.sourceRect.x + ((i % numCols) * tileWidth);
            float frameY = (-1 * ((origElement.uvRect.y * _textureSize.y) - _textureSize.y + origElement.sourceRect.height)) - origElement.sourceRect.y + ((i / numRows) * tileHeight);

            float frameW = tileWidth;
            float frameH = tileHeight;

            Rect uvRect = new Rect
            (
                frameX/_textureSize.x,
                ((_textureSize.y - frameY - frameH)/_textureSize.y),
                frameW/_textureSize.x,
                frameH/_textureSize.y
            );

            element.uvRect = uvRect;

            element.uvTopLeft.Set(uvRect.xMin,uvRect.yMax);
            element.uvTopRight.Set(uvRect.xMax,uvRect.yMax);
            element.uvBottomRight.Set(uvRect.xMax,uvRect.yMin);
            element.uvBottomLeft.Set(uvRect.xMin,uvRect.yMin);

            //the source size is the untrimmed size
            element.sourcePixelSize.x = tileWidth;
            element.sourcePixelSize.y = tileHeight;

            element.sourceSize.x = element.sourcePixelSize.x * scaleInverse;
            element.sourceSize.y = element.sourcePixelSize.y * scaleInverse;

            //this rect is the trimmed size and position relative to the untrimmed rect
            float rectX = origElement.sourceRect.x;
            float rectY = origElement.sourceRect.y;
            float rectW = tileWidth * scaleInverse;
            float rectH = tileHeight * scaleInverse;

            element.sourceRect = new Rect(rectX,rectY,rectW,rectH);

            _allElementsByName.Add(element.name, element);
            gid++;
        }
    }
Пример #17
0
        /**
         * @node If it's not null, it probably means we're on the top node and just
         *              got called from public Parse method
         * @parent If it's null, it means we're on the top node
         * @skip don't do a read, we're already on the next node and ready to process it
         *
         * If this method returns null, it means it has reached the end of the current
         * xml subtree (the end element of the parent node)
         **/
        static XamlNode Parse(XmlReader reader, XamlNode parent, XamlNode node,
                              NodeEvent evstart, NodeEvent evend,
                              AttributeEvent evattr, bool skip = false)
        {
            if (!skip)
            {
                reader.Read();
            }

            if (parent == null)
            {
                while (reader.NodeType != XmlNodeType.Element)
                {
                    if (!reader.Read())
                    {
                        return(null);
                    }
                }
            }
            else
            {
                do
                {
                    while (reader.NodeType != XmlNodeType.Element &&
                           reader.NodeType != XmlNodeType.EndElement &&
                           reader.NodeType != XmlNodeType.Text)
                    {
                        if (!reader.Read())
                        {
                            return(null);
                        }
                    }
                    if (reader.NodeType == XmlNodeType.Element &&
                        parent.top.IgnorablePrefixes.Contains(reader.Prefix))
                    {
                        reader.Skip();
                    }
                    else
                    {
                        break;
                    }
                } while (true);
            }

            if (reader.NodeType == XmlNodeType.EndElement)
            {
                return(null);
            }

            if (node == null)
            {
                node = new XamlNode();
            }

            node.Parsed = false;
            node.Ignore = false;

            if (!node.Initialized)
            {
                node.parent = parent;

                if (parent != null)
                {
                    node.top = parent.top;
                }
                else
                {
                    node.ignorablePrefixes = new List <string> ();
                    node.top = node;
                }

                node.type           = reader.NodeType;
                node.namespaceURI   = reader.NamespaceURI;
                node.prefix         = reader.Prefix;
                node.name           = reader.Name;
                node.localName      = reader.LocalName;
                node.IsEmptyElement = reader.IsEmptyElement;
                node.HasValue       = reader.HasValue;
                node.XmlSpace       = reader.XmlSpace;
                node.LineNumber     = -1;
                node.LinePosition   = -1;
                node.IsNsXaml       = node.NamespaceURI == XamlUri;
                node.IsNsClr        = node.NamespaceURI.StartsWith("clr-namespace");
                if (parent == null)
                {
                    node.DefaultXmlns = reader.GetAttribute("xmlns");
                }

                if (node.IsNsClr)
                {
                    int end = node.NamespaceURI.IndexOf(';');
                    if (end == -1)
                    {
                        end = node.NamespaceURI.Length;
                    }
                    node.ClrNamespace = node.NamespaceURI.Substring(14, end - 14);
                }

                if (node.IsNsClr && node.NamespaceURI.IndexOf(";assembly=") + 10 < node.NamespaceURI.Length)
                {
                    node.Assembly = node.NamespaceURI.Substring(node.NamespaceURI.IndexOf(";assembly=") + 10);
                }

                if (node.HasValue)
                {
                    node.val = reader.Value;
                }


                IXmlLineInfo linfo = reader as IXmlLineInfo;
                if (linfo != null)
                {
                    node.LineNumber   = linfo.LineNumber;
                    node.LinePosition = linfo.LinePosition;
                }

                if (reader.HasAttributes)
                {
                    string ig = reader.GetAttribute("Ignorable", IgnorableUri);
                    if (ig != null)
                    {
                        foreach (string s in ig.Split(' '))
                        {
                            node.IgnorablePrefixes.Add(s);
                        }
                    }

                    reader.MoveToFirstAttribute();

                    int count = 0;
                    do
                    {
                        // this filters out ignorable attributes
                        if (node.IgnorablePrefixes.Contains(reader.Prefix))
                        {
                            continue;
                        }

                        XamlAttribute ai = new XamlAttribute(reader)
                        {
                            Index = count++,
                        };

                        // an x: or equivalent attribute
                        ai.IsNsXaml = !ai.IsMapping && ai.NamespaceURI == XamlUri;
                        // an mc: or equivalent attribute (this attribute defines the list of ignorable prefixes)
                        ai.IsNsIgnorable = !ai.IsMapping && (ai.NamespaceURI == IgnorableUri || ai.Prefix == "mc");
                        // an xmlns:my='clr-namespace...' attribute
                        ai.IsNsClr = !ai.IsMapping && ai.NamespaceURI.StartsWith("clr-namespace");
                        if (ai.IsNsXaml && ai.LocalName == "Class")
                        {
                            node.Class = ai.Value;
                        }

                        if (ai.IsMapping)
                        {
                            if (node.top != node)
                            {
                                ai.Index = node.top.Attributes.Count;
                            }
                            node.top.Attributes [reader.Name] = ai;
                        }
                        else
                        {
                            if (ai.IsNsXaml)
                            {
                                if (ai.LocalName == "Key")
                                {
                                    node.X_Key = ai.Value;
                                }
                                else if (ai.LocalName == "Name")
                                {
                                    node.X_Name = ai.Value;
                                }
                            }
                            node.Attributes [reader.Name] = ai;
                        }
                    } while (reader.MoveToNextAttribute());

                    reader.MoveToElement();
                }

                node.Initialized = true;
            }

            if (evstart != null && (node.NodeType == XmlNodeType.Element || node.NodeType == XmlNodeType.Text))
            {
                evstart(node);
            }

            if (evattr != null)
            {
                foreach (XamlAttribute ai in node.Attributes.Values.Where(x => !x.IsNsIgnorable && !x.IsMapping))
                {
                    evattr(node, ai);
                }
            }

            if (node.Ignore)
            {
                node.outerXml         = reader.ReadOuterXml();
                cache [node.outerXml] = node;
                if (evend != null && node.NodeType == XmlNodeType.Element)
                {
                    evend(node);
                }
                return(node);
            }

            if (node.NodeType == XmlNodeType.Element && !node.IsEmptyElement)
            {
                XamlNode child = null;
                do
                {
                    child = Parse(reader, node, null, evstart, evend, evattr, child != null ? child.Ignore : false);
                    if (child != null)
                    {
                        child.Parsed = !child.Ignore;
                        node.Children.Add(child);
                    }
                } while (child != null);
            }

            if (evend != null && node.NodeType == XmlNodeType.Element)
            {
                evend(node);
            }

            return(node);
        }
 void IXmlSerializable.ReadXml(XmlReader reader)
 {
     reader.MoveToContent();
     _xmlDocument = new XmlDocument();
     _xmlDocument.LoadXml(reader.ReadOuterXml());
 }
Пример #19
0
        //Run SP XML reader (?)

        /*  No ADO.Net objects need to be declared from the calling code, since a string is returned.
         *  Since XML is returned the calling code needs to deal with XML.  The Stored Procedure MUST
         *  use the FOR XML clause so that only XML is returned to this DataAccessLayer
         */
        /// <summary>
        /// Executes a Stored Procedure and returns XML as a string.
        /// The Stored Procedure MUST use the 'FOR XML' clause and only return XML.
        /// </summary>
        /// <param name="SPName">string: The name of the Stored Procedure to execute</param>
        /// <returns>XML as string</returns>
        public string RunSPXMLReader(string SPName)
        {
            //Validate the SQL string (longer than 10 characters...)
            ValidateSPStatement(SPName);

            //All code past this point is included in the try...catch block to catch any exceptions that occur (including creating the connection)
            try
            {
                //Setting objects to handle parameters
                Parameter myGenericParameter;

                SqlParameter mySqlParameter;

                //The 'usedEnumerator makes it easy to step through the ArrayList of parameters
                IEnumerator usedEnumerator = _parameterList.GetEnumerator();

                //Check to see if this object has already been disposed
                if (_disposedBoolean)
                {
                    throw new ObjectDisposedException(_moduleName, "This object has already been disposed. You cannot reuse it.");
                }

                //Create connection
                _sqlConnection = new SqlConnection(_connectionString);

                //Define the command object and set the commandType to process a Stored Procedure
                _sqlCommand             = new SqlCommand(SPName, _sqlConnection);
                _sqlCommand.CommandType = CommandType.StoredProcedure;

                while (usedEnumerator.MoveNext())
                {
                    myGenericParameter = null;
                    myGenericParameter = (Parameter)usedEnumerator.Current;
                    //Convert the parameter to a SqlParameter
                    mySqlParameter = ConvertParameters(myGenericParameter);
                    _sqlCommand.Parameters.Add(mySqlParameter);
                }


                string returnXMLString = string.Empty;

                _sqlCommand.Connection.Open();
                _xmlReader = _sqlCommand.ExecuteXmlReader();

                //Loop through the reader and build the XML string.
                while (_xmlReader.Read())
                {
                    returnXMLString += _xmlReader.ReadOuterXml();
                }

                return(returnXMLString);
            }
            catch (Exception ex)
            {
                //Log the exception through our private LogException method
                LogException(ex);

                //If an exception occurs, it is passed back to the calling code with our custom message and specific exception information
                throw new Exception(_exceptionMessage, ex);
            }
            finally
            {
                //Check if the connection is still open - close it
                if (_sqlCommand.Connection.State == ConnectionState.Open)
                {
                    _sqlCommand.Connection.Close();
                }
            }
        }
Пример #20
0
        private List <FilenameProcessorRE> regxps; // only trustable while in DownloadRSS or its called functions

        // ReSharper disable once InconsistentNaming
        public bool DownloadRSS(string URL, List <FilenameProcessorRE> rexps)
        {
            this.regxps = rexps;

            System.Net.WebClient wc = new System.Net.WebClient();
            try
            {
                byte[] r = wc.DownloadData(URL);

                MemoryStream ms = new MemoryStream(r);

                XmlReaderSettings settings = new XmlReaderSettings
                {
                    IgnoreComments   = true,
                    IgnoreWhitespace = true
                };
                using (XmlReader reader = XmlReader.Create(ms, settings))
                {
                    reader.Read();
                    if (reader.Name != "xml")
                    {
                        return(false);
                    }

                    reader.Read();

                    if (reader.Name != "rss")
                    {
                        return(false);
                    }

                    reader.Read();

                    while (!reader.EOF)
                    {
                        if ((reader.Name == "rss") && (!reader.IsStartElement()))
                        {
                            break;
                        }

                        if (reader.Name == "channel")
                        {
                            if (!ReadChannel(reader.ReadSubtree()))
                            {
                                return(false);
                            }
                            reader.Read();
                        }
                        else
                        {
                            reader.ReadOuterXml();
                        }
                    }
                }
            }
            catch
            {
                return(false);
            }
            finally
            {
                this.regxps = null;
            }

            return(true);
        }
Пример #21
0
        public void ReadXml(XmlReader xmlReader, PointF scale, TimestampMapper timestampMapper)
        {
            if (xmlReader.MoveToAttribute("id"))
            {
                identifier = new Guid(xmlReader.ReadContentAsString());
            }

            if (xmlReader.MoveToAttribute("name"))
            {
                name = xmlReader.ReadContentAsString();
            }

            xmlReader.ReadStartElement();

            while (xmlReader.NodeType == XmlNodeType.Element)
            {
                switch (xmlReader.Name)
                {
                case "Start":
                {
                    PointF p = XmlHelper.ParsePointF(xmlReader.ReadElementContentAsString());
                    points["a"] = p.Scale(scale.X, scale.Y);
                    break;
                }

                case "End":
                {
                    PointF p = XmlHelper.ParsePointF(xmlReader.ReadElementContentAsString());
                    points["b"] = p.Scale(scale.X, scale.Y);
                    break;
                }

                case "ExtraData":
                {
                    TypeConverter enumConverter = TypeDescriptor.GetConverter(typeof(TrackExtraData));
                    trackExtraData = (TrackExtraData)enumConverter.ConvertFromString(xmlReader.ReadElementContentAsString());
                    break;
                }

                case "MeasureLabel":
                {
                    miniLabel = new MiniLabel(xmlReader, scale);
                    break;
                }

                case "DrawingStyle":
                    style = new DrawingStyle(xmlReader);
                    BindStyle();
                    break;

                case "InfosFading":
                    infosFading.ReadXml(xmlReader);
                    break;

                case "Measure":
                    xmlReader.ReadOuterXml();
                    break;

                default:
                    string unparsed = xmlReader.ReadOuterXml();
                    log.DebugFormat("Unparsed content in KVA XML: {0}", unparsed);
                    break;
                }
            }

            xmlReader.ReadEndElement();
            initializing       = false;
            measureInitialized = true;
            miniLabel.SetAttach(GetMiddlePoint(), false);
            miniLabel.BackColor = styleHelper.Color;
            SignalAllTrackablePointsMoved();
        }
        public void Add_Invoke_ReturnsExpected()
        {
            SyndicationElementExtensionCollection elementExtensions = new SyndicationCategory().ElementExtensions;

            elementExtensions.Add(new ExtensionObject {
                Value = 10
            });
            elementExtensions.Add(new SyndicationElementExtension(new ExtensionObject {
                Value = 11
            }));
            using (var stringReader = new StringReader(@"<SyndicationElementExtensionCollectionTests.ExtensionObject xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Value>12</Value></SyndicationElementExtensionCollectionTests.ExtensionObject>"))
                using (XmlReader reader = XmlReader.Create(stringReader))
                {
                    elementExtensions.Add(reader);
                }
            elementExtensions.Add(new ExtensionObject {
                Value = 13
            }, new DataContractSerializer(typeof(ExtensionObject)));
            elementExtensions.Add(new ExtensionObject {
                Value = 14
            }, (DataContractSerializer)null);
            elementExtensions.Add(new ExtensionObject {
                Value = 15
            }, new XmlSerializer(typeof(ExtensionObject)));
            elementExtensions.Add(new ExtensionObject {
                Value = 16
            }, (XmlSerializer)null);
            elementExtensions.Add("outerName", "outerNamespace", new ExtensionObject {
                Value = 17
            });
            elementExtensions.Add("outerName", "outerNamespace", new ExtensionObject {
                Value = 18
            }, new DataContractSerializer(typeof(ExtensionObject)));
            elementExtensions.Add("outerName", "outerNamespace", new ExtensionObject {
                Value = 19
            }, null);

            Assert.Equal(10, elementExtensions.Count);

            using (XmlReader reader = elementExtensions.GetReaderAtElementExtensions())
            {
                Assert.Equal(@"<SyndicationElementExtensionCollectionTests.ExtensionObject xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Value>10</Value></SyndicationElementExtensionCollectionTests.ExtensionObject>", reader.ReadOuterXml());
            }
        }
Пример #23
0
        // ======================== Getters and setters =======================================

        // ======================== Public methods ============================================

        /* -------------------------------------------------------------------------------------
        * Name:        ConvertOneOpsToFolia
        * Goal:        Convert one opensubtitle gz file to a folia.xml file
        * Parameters:  sFileIn     - File to be processed
        *              sDirIn      - Directory under which the input files are located
        *              sDirOut     - Directory where the output files should come
        *              bForce      - Create result, even though it exists already
        *              bMulti      - Only do multi-part files
        *              bIsDebug    - Debugging mode on or off
        * History:
        * 27/jan/2016 ERK Created
        *  ------------------------------------------------------------------------------------- */
        public bool ConvertOneOpsToFolia(String sFileIn, String sDirIn, String sDirOut, bool bForce,
                                         bool bMulti, bool bIsDebug)
        {
            // XmlReader rdOps = null;
            XmlWriter   wrFolia  = null;
            List <Sent> lSentBuf = new List <Sent>(); // Buffer containing sentences and words

            try {
                // Validate
                if (!File.Exists(sFileIn))
                {
                    return(false);
                }
                if (!Directory.Exists(sDirOut))
                {
                    return(false);
                }

                // If the input file cannot be read, then skip it
                if (!util.General.CanReadFile(sFileIn))
                {
                    return(true);
                }

                // Make sure dirout does not contain a trailing /
                if (sDirOut.EndsWith("/") || sDirOut.EndsWith("\\"))
                {
                    sDirOut = sDirOut.Substring(0, sDirOut.Length - 1);
                }

                // Retrieve the idmovie and the movie's name from the file name
                String sIdMovie = ""; String sMovieName = ""; String sMovieYear = "";
                if (!getMovieNameId(sFileIn, ref sMovieName, ref sIdMovie, ref sMovieYear))
                {
                    return(false);
                }

                // Get the destination directory
                String sDst    = sDirOut + "/" + sFileIn.Substring(sDirIn.Length + 1);
                String sDstDir = Path.GetDirectoryName(sDst);
                // Check existence of destination directory
                if (!Directory.Exists(sDstDir))
                {
                    Directory.CreateDirectory(sDstDir);
                }

                // Create a destination file name inside [sDirOut]
                String sFileName = Path.GetFileNameWithoutExtension(sFileIn);
                string sFileBase = Path.GetFullPath(Path.GetDirectoryName(sFileIn) + "/" + Path.GetFileName(sFileIn));
                String sBare     = sFileName;
                int    iUs       = sBare.IndexOf('_');
                int    iVersion  = 1; // Default version number
                int    iMax      = 1; // Maximum version number
                int    iSubtitle = 0; // Default subtitles.org number
                if (iUs >= 0)
                {
                    sBare = sBare.Substring(0, iUs);
                    // Get to the second part
                    String sSecond = sFileName.Substring(iUs + 1);
                    // Find two numbers there
                    Match mcOne = Regex.Match(sSecond, "\\d+");
                    if (!mcOne.Success)
                    {
                        errHandle.DoError("ConvertOneOpsToFolia", "cannot get number from [" + sSecond + "]");
                        return(false);
                    }
                    // Get first number
                    iVersion = Convert.ToInt32(mcOne.Value);
                    // Go to next number
                    mcOne = mcOne.NextMatch();
                    if (!mcOne.Success)
                    {
                        errHandle.DoError("ConvertOneOpsToFolia", "cannot get number from [" + sSecond + "]");
                        return(false);
                    }
                    iMax = Convert.ToInt32(mcOne.Value);

                    /*
                     * iVersion = Convert.ToInt32(sFileName.Substring(iUs + 1, 1));
                     * iMax = Convert.ToInt32(sFileName.Substring(iUs + 4, 1));
                     */
                }

                // Check if we need to continue
                if (bMulti && iMax == 1)
                {
                    debug("Skipping (non-multi): " + sFileIn);
                    return(true);
                }

                UInt64 iNumber;
                if (UInt64.TryParse(sBare, out iNumber))
                {
                    iSubtitle = Convert.ToInt32(iNumber);
                    sBare     = "S-O_" + iNumber.ToString("D8");
                }
                else
                {
                    sBare = "S-O_" + sBare;
                }
                // sBare = "S-O_" + string.Format("00000000", ((int) sBare));
                String sDstBare = Path.GetFullPath(sDstDir + "/" + sBare);
                // String sFileTmp = Path.GetFullPath(sDstBare + ".xml");
                String sFileOut  = Path.GetFullPath(sDstBare + ".folia.xml");
                String sFileOutZ = Path.GetFullPath(sDstBare + ".folia.xml.gz");

                // Check if output file already exists
                if (!bForce && File.Exists(sFileOutZ))
                {
                    debug("Skipping existing: " + sFileIn);
                    return(true);
                }

                // Other initialisations before the conversion starts
                OpsToFolia objOpsFolia = new OpsToFolia(errHandle);
                // objOpsFolia.setCurrentSrcFile(sFileTmp);
                objOpsFolia.setCurrentSrcFile("");
                int iSentNum = 0;
                // Set up an XML writer according to our liking
                XmlWriterSettings wrSet = new XmlWriterSettings();
                wrSet.Indent            = true;
                wrSet.NewLineHandling   = NewLineHandling.Replace;
                wrSet.NamespaceHandling = NamespaceHandling.OmitDuplicates;
                wrSet.ConformanceLevel  = ConformanceLevel.Document;

                /*
                 * // DOuble check to see if the conversion was already done
                 * if (!bForce && File.Exists(sFileOut) && !File.Exists(sFileTmp)) return true;
                 * // If this is a different version, and we already have a copy, then skip it
                 * if (iVersion > 1 && File.Exists(sFileOut) && !File.Exists(sFileTmp)) return true;
                 * */

                // Create a temporary folia output file with the bare essentials
                String sFileTmpF = sFileOut + ".tmp";
                // Bare folia text
                String sBareFolia = objOpsFolia.getIntro(sBare, sIdMovie, "", sMovieYear, iSubtitle, iVersion, iMax) +
                                    objOpsFolia.getExtro();
                // Write this text to a file
                XmlDocument pdxBareF = new XmlDocument();
                try {
                    pdxBareF.LoadXml(sBareFolia);
                } catch (Exception ex) {
                    errHandle.DoError("ConvertOneOpsToFolia/BareFolia problem", ex); // Provide standard error message
                    return(false);
                }
                // Adapt the moviename
                XmlNamespaceManager nsBare = new XmlNamespaceManager(pdxBareF.NameTable);
                nsBare.AddNamespace("b", pdxBareF.DocumentElement.NamespaceURI);
                XmlNode ndxMvName = pdxBareF.SelectSingleNode("./descendant::b:meta[@id='name']", nsBare);
                if (ndxMvName != null)
                {
                    ndxMvName.InnerText = sMovieName;
                }
                pdxBareF.Save(sFileTmpF);
                // Don't need objOpsFolia anymore
                objOpsFolia = null;

                // Convert the temporary files to the output file
                // (1) Open the input file
                debug("Starting: " + sFileIn);

                // (2) Make sure we have a 'global' start and finish time
                String sTimeStart = ""; String sTimeEnd = "";
                String sTimeBkup = "";    // Backup time for when we get confused
                String sLineSrt  = "";    // Line number within the SRT file
                bool   bStart    = false; // This word has the time-start marker
                bool   bEnd      = false; // This word has the time-end marker

                // Determine the file name template we will be looking for
                String sFileInTemplate = sFileName.Replace("1of" + iMax, "*of" + iMax) + ".gz";
                // Get all the files fulfilling this template
                String[] arFileIn = Directory.GetFiles(Path.GetDirectoryName(sFileIn), sFileInTemplate, SearchOption.TopDirectoryOnly);
                // Make sure the files are sorted correctly
                List <String> lFileIn = arFileIn.ToList <String>();
                lFileIn.Sort();
                int iFile = 0; // Number of the file from the [lFileIn] list

                // Skip those that do not have the correct number of parts
                if (iMax != lFileIn.Count)
                {
                    debug("--Part/Count mismatch");
                    return(true);
                }

                // (3) Open the bare FoLiA file for input
                using (StreamReader rdFileTmpF = new StreamReader(sFileTmpF))
                    using (XmlReader rdFolia = XmlReader.Create(rdFileTmpF))

                        // (5) Create an output file
                        // using (StreamWriter wrFileTmpOut = new StreamWriter(sFileOut))
                        //  using (wrFolia = XmlWriter.Create(wrFileTmpOut, wrSet)) {
                        using (wrFolia = new FoliaXmlWriter(sFileOut, Encoding.UTF8)) {
                            // (6) Walk through the bare folia input file
                            while (!rdFolia.EOF && rdFolia.Read())
                            {
                                // (7) Check what kind of input this is
                                // Note: we need to pause after reading the <p> start element
                                if (rdFolia.IsStartElement("p"))
                                {
                                    // (8) Do make sure that we WRITE the start element away
                                    WriteShallowNode(rdFolia, wrFolia);

                                    // Check the index
                                    if (iFile < 0 || iFile >= lFileIn.Count)
                                    {
                                        // Cannot do this
                                        errHandle.DoError("ConvertOneOpsToFolia", "iFile=" + iFile + " but lFileIn=" + lFileIn.Count);
                                    }
                                    // Retrieve the next input file from the list
                                    String sFileTmp = lFileIn[iFile].Replace(".xml.gz", "xml");
                                    // Unzip the file
                                    if (!util.General.DecompressFile(lFileIn[iFile], sFileTmp))
                                    {
                                        return(false);
                                    }

                                    // Increment the file number for the next run and reset the sentence number
                                    iFile += 1; iSentNum = 0;

                                    // (4) Open the open-subtitle xml file for input
                                    using (StreamReader rdFileTmp = new StreamReader(sFileTmp))
                                        using (XmlReader rdOps = XmlReader.Create(rdFileTmp)) {
                                            // (9) Walk through the *actual* open-subtitle input file
                                            while (!rdOps.EOF && rdOps.Read())
                                            {
                                                // (10) Check what this is
                                                if (rdOps.IsStartElement("s"))
                                                {
                                                    // Read the <s> element as one string
                                                    String sWholeS = rdOps.ReadOuterXml();
                                                    iSentNum++;
                                                    // Process the <s> element:
                                                    // (1) put it into an XmlDocument
                                                    XmlDocument pdxSrc = new XmlDocument();
                                                    pdxSrc.LoadXml(sWholeS);
                                                    // (2) Create a namespace mapping for the opensubtitles *source* xml document
                                                    XmlNamespaceManager nsOps = new XmlNamespaceManager(pdxSrc.NameTable);
                                                    nsOps.AddNamespace("df", pdxSrc.DocumentElement.NamespaceURI);
                                                    // (3) Create a sentence identifier
                                                    String sSentId = sBare + ".p." + iFile + ".s." + iSentNum;
                                                    // (4) The first <s> should at least have some <w> elements
                                                    if (iSentNum == 1)
                                                    {
                                                        // Check out first sentence
                                                        if (pdxSrc.SelectSingleNode("./descendant::df:w", nsOps) == null)
                                                        {
                                                            // Skip this file -- it contains RAW info, no <w> elements
                                                            return(true);
                                                        }
                                                    }
                                                    // (5) Create a new sentence in the buffer
                                                    Sent oSent = new Sent(sSentId);
                                                    lSentBuf.Add(oSent);
                                                    // (6) Process all *descendants* of this <s> one-by-one
                                                    XmlNodeList ndChild = pdxSrc.SelectNodes("./descendant-or-self::df:s/descendant::df:*", nsOps);
                                                    int         iWord   = 0;
                                                    for (int i = 0; i < ndChild.Count; i++)
                                                    {
                                                        // Get this child
                                                        XmlNode ndThis = ndChild.Item(i);
                                                        // Action depends on the type of child this is
                                                        switch (ndThis.Name)
                                                        {
                                                        case "time":
                                                            // Get the time id and value
                                                            String sTimeId  = ndThis.Attributes["id"].Value;
                                                            String sTimeVal = ndThis.Attributes["value"].Value;
                                                            // Is this the *start* or *end* time?
                                                            if (sTimeId.EndsWith("S"))
                                                            {
                                                                // Keep track of the latest *start* time and reset the end time
                                                                sTimeStart = sTimeVal; sTimeEnd = ""; bStart = true;
                                                                sTimeBkup  = sTimeVal;
                                                                // Get the SRT line number
                                                                sLineSrt = sTimeId.Substring(1, sTimeId.Length - 2);
                                                            }
                                                            else
                                                            {
                                                                // Add the end-time
                                                                sTimeEnd = sTimeVal;
                                                                // Reset the starting time
                                                                sTimeStart = "";
                                                                bEnd       = true;
                                                                if (bEnd)
                                                                {
                                                                    // Reset flag
                                                                    bEnd = false;
                                                                    // Add mark for starting
                                                                    lSentBuf[lSentBuf.Count - 1].markEnd();
                                                                }
                                                                // Process the sentence buffer
                                                                // (a) Process all previous sentences
                                                                int iCount = lSentBuf.Count;
                                                                if (!FlushOpsToFolia(ref lSentBuf, ref wrFolia, iCount - 1, sTimeEnd, sTimeBkup))
                                                                {
                                                                    return(false);
                                                                }
                                                                // (b) Process the words in the current sentence
                                                                List <WordBuf> lCurrent = lSentBuf[lSentBuf.Count - 1].words;
                                                                for (int j = 0; j < lCurrent.Count; j++)
                                                                {
                                                                    // Check if this word needs to have an end-time
                                                                    if (lCurrent[j].e == "")
                                                                    {
                                                                        lCurrent[j].e = sTimeEnd;
                                                                    }
                                                                }
                                                            }
                                                            break;

                                                        case "i": // Some have an <i> tag to indicate what goes on one line: ignore
                                                            break;

                                                        case "w":
                                                            // Process this word
                                                            iWord++;
                                                            // Get the text of this word
                                                            String sWord = ndThis.InnerText;
                                                            // Create an identifier for this word
                                                            // String sWordId = sSentId + ".w." + iWord;
                                                            String sWordCl = (util.General.DoLike(sWord, ".|,|...|..|-|?|!|\"|'|:|;|(|)")) ? "Punct" : "Vern";
                                                            // Add this word to the buffer of this current sentence
                                                            lSentBuf[lSentBuf.Count - 1].addWord(sWord, sWordCl);
                                                            // Add the start-time to this word
                                                            lSentBuf[lSentBuf.Count - 1].addStart(sTimeStart);
                                                            // Add the SRT number to this word
                                                            lSentBuf[lSentBuf.Count - 1].addLine(sLineSrt);
                                                            if (bStart)
                                                            {
                                                                // Reset flag
                                                                bStart = false;
                                                                // Add mark for starting
                                                                lSentBuf[lSentBuf.Count - 1].markStart();
                                                            }

                                                            break;

                                                        default:
                                                            // No idea what to do here -- just skip??
                                                            break;
                                                        }
                                                    }
                                                }
                                            } // End while
                                            // Process any remaining sentences
                                            if (!FlushOpsToFolia(ref lSentBuf, ref wrFolia, lSentBuf.Count, sTimeEnd, sTimeBkup))
                                            {
                                                return(false);
                                            }
                                            rdOps.Close(); // rdOps.Dispose();
                                            rdFileTmp.Close();
                                            // Remove the temporary file
                                            File.Delete(sFileTmp);
                                        }

                                    // }
                                }
                                else
                                {
                                    // Process reading the input
                                    WriteShallowNode(rdFolia, wrFolia);
                                }
                            }
                            // debug("Point 3: locked = " + util.General.IsFileLocked(sFileTmp));
                            wrFolia.Flush();
                            wrFolia.Close(); // wrFolia.Dispose();
                            rdFolia.Close(); // rdFolia.Dispose();
                            rdFileTmpF.Close();
                            // debug("Point 4: locked = " + util.General.IsFileLocked(sFileTmp));
                        }

                // Remove the temporary Folia file
                File.Delete(sFileTmpF);

                // Convert to compressed-file
                if (!util.General.CompressFile(sFileOut, sFileOutZ))
                {
                    return(false);
                }
                // Remove the original output
                File.Delete(sFileOut);

                // Return positively
                return(true);
            } catch (Exception ex) {
                errHandle.DoError("ConvertOneOpsToFolia", ex); // Provide standard error message
                return(false);

                throw;
            }
        }
Пример #24
0
 private void Bar(XmlReader reader)
 {
     reader.Read();
     string foo = reader.ReadOuterXml();
     CError.Compare(foo, "<device xmlns=\"http://www.test.com/\">        <thing>1</thing>    </device>",
         "<device xmlns=\"http://www.test.com/\"><thing>1</thing></device>", "mismatch");
 }
Пример #25
0
 private string GetXmlOfElement(XmlReader xrdrSub)
 {
     return(xrdrSub.ReadOuterXml());
 }
Пример #26
0
        public void ReadXml(XmlReader xmlReader)
        {
            styleElements.Clear();

            xmlReader.ReadStartElement();       // <ToolPreset Key="ToolName"> or <DrawingStyle>
            while (xmlReader.NodeType == XmlNodeType.Element)
            {
                AbstractStyleElement styleElement = null;
                string key = xmlReader.GetAttribute("Key");

                switch (xmlReader.Name)
                {
                case "Color":
                    styleElement = new StyleElementColor(xmlReader);
                    break;

                case "FontSize":
                    styleElement = new StyleElementFontSize(xmlReader);
                    break;

                case "PenSize":
                    styleElement = new StyleElementPenSize(xmlReader);
                    break;

                case "LineSize":
                    styleElement = new StyleElementLineSize(xmlReader);
                    break;

                case "LineShape":
                    styleElement = new StyleElementLineShape(xmlReader);
                    break;

                case "Arrows":
                    styleElement = new StyleElementLineEnding(xmlReader);
                    break;

                case "TrackShape":
                    styleElement = new StyleElementTrackShape(xmlReader);
                    break;

                case "GridDivisions":
                    styleElement = new StyleElementGridDivisions(xmlReader);
                    break;

                case "Curved":
                    styleElement = new StyleElementCurved(xmlReader);
                    break;

                default:
                    log.ErrorFormat("Could not import style element \"{0}\"", xmlReader.Name);
                    log.ErrorFormat("Content was: {0}", xmlReader.ReadOuterXml());
                    break;
                }

                if (styleElement != null)
                {
                    styleElements.Add(key, styleElement);
                }
            }

            xmlReader.ReadEndElement();
        }
Пример #27
0
        public static void XmlTest()
        {
            string tempTable      = "xml_" + Guid.NewGuid().ToString().Replace('-', '_');
            string initStr        = "create table " + tempTable + " (xml_col XML)";
            string insertNormStr  = "INSERT " + tempTable + " VALUES('<doc>Hello World</doc>')";
            string insertParamStr = "INSERT " + tempTable + " VALUES(@x)";
            string queryStr       = "select * from " + tempTable;

            using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString))
            {
                conn.Open();

                SqlCommand cmd = conn.CreateCommand();

                cmd.CommandText = initStr;
                cmd.ExecuteNonQuery();

                try
                {
                    cmd.CommandText = insertNormStr;
                    cmd.ExecuteNonQuery();

                    SqlCommand cmd2 = new SqlCommand(insertParamStr, conn);

                    cmd2.Parameters.Add("@x", SqlDbType.Xml);
                    XmlReader xr = XmlReader.Create("data.xml");
                    cmd2.Parameters[0].Value = new SqlXml(xr);
                    cmd2.ExecuteNonQuery();

                    cmd.CommandText = queryStr;

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        int      currentValue   = 0;
                        string[] expectedValues =
                        {
                            "<doc>Hello World</doc>",
                            "<NewDataSet><builtinCLRtypes><colsbyte>1</colsbyte><colbyte>2</colbyte><colint16>-20</colint16><coluint16>40</coluint16><colint32>-300</colint32><coluint32>300</coluint32><colint64>-4000</colint64><coluint64>4000</coluint64><coldecimal>50000.01</coldecimal><coldouble>600000.987</coldouble><colsingle>70000.9</colsingle><colstring>string variable</colstring><colboolean>true</colboolean><coltimespan>P10675199DT2H48M5.4775807S</coltimespan><coldatetime>9999-12-30T23:59:59.9999999-08:00</coldatetime><colGuid>00000001-0002-0003-0405-060708010101</colGuid><colbyteArray>AQIDBAUGBwgJCgsMDQ4PEA==</colbyteArray><colUri>http://www.abc.com/</colUri><colobjectsbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"byte\">1</colobjectsbyte><colobjectbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedByte\">2</colobjectbyte><colobjectint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"short\">-20</colobjectint16><colobjectuint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedShort\">40</colobjectuint16><colobjectint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"int\">-300</colobjectint32><colobjectuint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedInt\">300</colobjectuint32><colobjectint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"long\">-4000</colobjectint64><colobjectuint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedLong\">4000</colobjectuint64><colobjectdecimal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"decimal\">50000.01</colobjectdecimal><colobjectdouble xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"double\">600000.987</colobjectdouble><colobjectsingle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"float\">70000.9</colobjectsingle><colobjectstring xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"string\">string variable</colobjectstring><colobjectboolean xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"boolean\">true</colobjectboolean><colobjecttimespan xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"duration\">P10675199DT2H48M5.4775807S</colobjecttimespan><colobjectdatetime xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"dateTime\">9999-12-30T23:59:59.9999999-08:00</colobjectdatetime><colobjectguid xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" msdata:InstanceType=\"System.Guid\">00000001-0002-0003-0405-060708010101</colobjectguid><colobjectbytearray xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"base64Binary\">AQIDBAUGBwgJCgsMDQ4PEA==</colobjectbytearray><colobjectUri xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"anyURI\">http://www.abc.com/</colobjectUri></builtinCLRtypes><builtinCLRtypes><colbyte>2</colbyte><colint16>-20</colint16><colint32>-300</colint32><coluint32>300</coluint32><coluint64>4000</coluint64><coldecimal>50000.01</coldecimal><coldouble>600000.987</coldouble><colsingle>70000.9</colsingle><colboolean>true</colboolean><colobjectsbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"byte\">11</colobjectsbyte><colobjectbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedByte\">22</colobjectbyte><colobjectint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"short\">-200</colobjectint16><colobjectuint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedShort\">400</colobjectuint16><colobjectint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"int\">-3000</colobjectint32><colobjectuint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedInt\">3000</colobjectuint32><colobjectint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"long\">-40000</colobjectint64><colobjectuint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedLong\">40000</colobjectuint64><colobjectdecimal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"decimal\">500000.01</colobjectdecimal><colobjectdouble xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"double\">6000000.987</colobjectdouble><colobjectsingle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"float\">700000.9</colobjectsingle><colobjectstring xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"string\">string variable 2</colobjectstring><colobjectboolean xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"boolean\">false</colobjectboolean><colobjecttimespan xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"duration\">-P10675199DT2H48M5.4775808S</colobjecttimespan><colobjectdatetime xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"dateTime\">0001-01-01T00:00:00.0000000-08:00</colobjectdatetime><colobjectguid xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" msdata:InstanceType=\"System.Guid\">00000002-0001-0001-0807-060504030201</colobjectguid><colobjectbytearray xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"base64Binary\">EA8ODQwLCgkIBwYFBAMCAQ==</colobjectbytearray></builtinCLRtypes></NewDataSet>"
                        };

                        while (reader.Read())
                        {
                            Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected");

                            SqlXml sx = reader.GetSqlXml(0);
                            xr = sx.CreateReader();
                            xr.Read();

                            DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], xr.ReadOuterXml(), "FAILED: Did not receive expected data");
                        }
                    }
                }
                finally
                {
                    cmd.CommandText = "drop table " + tempTable;
                    cmd.ExecuteNonQuery();
                }
            }
        }
Пример #28
0
        /// <summary>
        /// Reads XML conforming to https://www.w3.org/TR/2001/PR-xmldsig-core-20010820/#sec-KeyInfo
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> pointing positioned on a &lt;KeyInfo> element.</param>
        /// <exception cref="ArgumentNullException">if <paramref name="reader"/> is null.</exception>
        /// <exception cref="XmlReadException">if there is a problem reading the XML.</exception>
        /// <remarks>Only handles IssuerSerial, Ski, SubjectName, Certificate. Unsupported types are skipped. Only a X509 data element is supported.</remarks>
        public virtual KeyInfo ReadKeyInfo(XmlReader reader)
        {
            XmlUtil.CheckReaderOnEntry(reader, XmlSignatureConstants.Elements.KeyInfo, XmlSignatureConstants.Namespace);

            var keyInfo = new KeyInfo
            {
                Prefix = reader.Prefix
            };

            try
            {
                bool isEmptyElement = reader.IsEmptyElement;

                // <KeyInfo>
                reader.ReadStartElement();
                while (reader.IsStartElement())
                {
                    // <X509Data>
                    if (reader.IsStartElement(XmlSignatureConstants.Elements.X509Data, XmlSignatureConstants.Namespace))
                    {
                        keyInfo.X509Data.Add(ReadX509Data(reader));
                    }
                    // <RetrievalMethod>
                    else if (reader.IsStartElement(XmlSignatureConstants.Elements.RetrievalMethod, XmlSignatureConstants.Namespace))
                    {
                        keyInfo.RetrievalMethodUri = reader.GetAttribute(XmlSignatureConstants.Attributes.URI);
                        reader.ReadOuterXml();
                    }
                    // <KeyName>
                    else if (reader.IsStartElement(XmlSignatureConstants.Elements.KeyName, XmlSignatureConstants.Namespace))
                    {
                        keyInfo.KeyName = reader.ReadElementContentAsString(XmlSignatureConstants.Elements.KeyName, XmlSignatureConstants.Namespace);
                    }
                    // <KeyValue>
                    else if (reader.IsStartElement(XmlSignatureConstants.Elements.KeyValue, XmlSignatureConstants.Namespace))
                    {
                        reader.ReadStartElement(XmlSignatureConstants.Elements.KeyValue, XmlSignatureConstants.Namespace);
                        if (reader.IsStartElement(XmlSignatureConstants.Elements.RSAKeyValue, XmlSignatureConstants.Namespace))
                        {
                            // Multiple RSAKeyValues were found
                            if (keyInfo.RSAKeyValue != null)
                            {
                                throw XmlUtil.LogReadException(LogMessages.IDX30015, XmlSignatureConstants.Elements.RSAKeyValue);
                            }

                            keyInfo.RSAKeyValue = ReadRSAKeyValue(reader);
                        }
                        else
                        {
                            // Skip the element since it is not an <RSAKeyValue>
                            LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml());
                        }

                        // </KeyValue>
                        reader.ReadEndElement();
                    }
                    else
                    {
                        // Skip the element since it is not one of  <RetrievalMethod>, <X509Data>, <KeyValue>
                        LogHelper.LogWarning(LogMessages.IDX30300, reader.ReadOuterXml());
                    }
                }

                // </KeyInfo>
                if (!isEmptyElement)
                {
                    reader.ReadEndElement();
                }
            }
            catch (Exception ex)
            {
                if (ex is XmlReadException)
                {
                    throw;
                }

                throw XmlUtil.LogReadException(LogMessages.IDX30017, ex, XmlSignatureConstants.Elements.KeyInfo, ex);
            }

            return(keyInfo);
        }
Пример #29
0
        private void ReadContent(XmlReader reader, Configuration config, bool overrideAllowed, bool root)
        {
            while (reader.NodeType != XmlNodeType.EndElement && reader.NodeType != XmlNodeType.None)
            {
                if (reader.NodeType != XmlNodeType.Element)
                {
                    reader.Skip();
                    continue;
                }

                if (reader.LocalName == "dllmap")
                {
                    reader.Skip();
                    continue;
                }

                if (reader.LocalName == "location")
                {
                    if (!root)
                    {
                        ThrowException("<location> elements are only allowed in <configuration> elements.", reader);
                    }

                    string allowOverrideAttr = reader.GetAttribute("allowOverride");
                    var    allowOverride     = string.IsNullOrEmpty(allowOverrideAttr) ||
                                               bool.Parse(allowOverrideAttr);
                    string path = reader.GetAttribute("path");
                    if (!string.IsNullOrEmpty(path) && path[0] != '.')
                    {
                        string xml      = reader.ReadOuterXml();
                        var    pathList = path.Split(',');
                        foreach (var p in pathList)
                        {
                            var tpath = p.Trim();
                            if (config.Locations.Find(tpath) != null)
                            {
                                ThrowException("Sections must only appear once per config file.", reader);
                            }

                            var loc = new ConfigurationLocation(tpath, xml, config, allowOverride);
                            config.Locations.Add(loc);
                        }
                    }
                    else
                    {
                        ReadData(config, reader, allowOverride);
                    }
                    continue;
                }

                var data = GetConfigInfo(reader, this);
                if (data != null)
                {
                    data.ReadData(config, reader, overrideAllowed);
                }
                else
                {
                    ThrowException("Unrecognized configuration section <" + reader.LocalName + ">", reader);
                }
            }
        }
Пример #30
0
        private void Load(XmlReader r)
        {
            // Note: the order of tags is somewhat important.
            // Image size and the timing information must be at the top so we can adapt
            // all coordinates and times found in the file to the existing video.
            log.Debug("Importing Metadata from KVA file.");

            r.MoveToContent();

            if (!(r.Name == "KinoveaVideoAnalysis"))
            {
                return;
            }

            PointF scaling = PointF.Empty;

            r.ReadStartElement();
            r.ReadElementContentAsString("FormatVersion", "");

            while (r.NodeType == XmlNodeType.Element)
            {
                switch (r.Name)
                {
                case "Producer":
                    r.ReadElementContentAsString();
                    break;

                case "OriginalFilename":
                    inputFileName = r.ReadElementContentAsString();
                    break;

                case "FullPath":
                    string fullPath = r.ReadElementContentAsString();
                    if (string.IsNullOrEmpty(metadata.FullPath))
                    {
                        metadata.FullPath = fullPath;
                    }
                    break;

                case "GlobalTitle":
                    metadata.GlobalTitle = r.ReadElementContentAsString();
                    break;

                case "ImageSize":
                    inputImageSize = XmlHelper.ParseSize(r.ReadElementContentAsString());
                    scaling        = GetScaling();
                    break;

                case "AverageTimeStampsPerFrame":
                    inputAverageTimeStampsPerFrame = r.ReadElementContentAsLong();
                    break;

                case "FirstTimeStamp":
                    inputFirstTimeStamp = r.ReadElementContentAsLong();
                    break;

                case "CaptureFramerate":
                    metadata.CalibrationHelper.CaptureFramesPerSecond = r.ReadElementContentAsDouble();
                    break;

                case "UserFramerate":
                    metadata.UserInterval = 1000 / r.ReadElementContentAsDouble();
                    break;

                case "SelectionStart":
                    inputSelectionStart = r.ReadElementContentAsLong();
                    break;

                case "TimeOrigin":
                    metadata.TimeOrigin = RemapTimestamp(r.ReadElementContentAsLong(), false);
                    break;

                case "Calibration":
                    metadata.CalibrationHelper.ReadXml(r, scaling, inputImageSize);
                    break;

                case "Keyframes":
                    ParseKeyframes(r);
                    break;

                case "Tracks":
                    ParseTracks(r, scaling);
                    break;

                case "Chronos":
                    ParseChronos(r, scaling);
                    break;

                case "Spotlights":
                    metadata.SpotlightManager.ReadXml(r, scaling, RemapTimestamp, metadata);
                    break;

                case "AutoNumbers":
                    metadata.AutoNumberManager.ReadXml(r, scaling, RemapTimestamp, metadata);
                    break;

                case "CoordinateSystem":
                    metadata.DrawingCoordinateSystem.ReadXml(r);
                    break;

                case "Trackability":
                    metadata.TrackabilityManager.ReadXml(r, scaling, RemapTimestamp);
                    break;

                default:
                    // Skip the unparsed nodes.
                    string unparsed = r.ReadOuterXml();
                    log.DebugFormat("Unparsed content in KVA XML: {0}", unparsed);
                    break;
                }
            }

            r.ReadEndElement();
        }
Пример #31
0
        public Dictionary <string, object> ReadFromDataRowXML(string s)//从生成的数据表里面恢复数据
        {
            StringReader xs     = new StringReader(s);
            XmlReader    reader = XmlReader.Create(xs);

            if (!reader.ReadToFollowing("DataRow"))
            {
                return(null);
            }

            Dictionary <string, object> rd = new Dictionary <string, object>();
            bool IsNotEnd = reader.Read();

            while (IsNotEnd)//进入当前的对象进行读取,主要是子标签
            {
                switch (reader.NodeType)
                {
                case XmlNodeType.Element:
                    if (!reader.HasAttributes)
                    {
                        reader.ReadOuterXml();
                    }
                    else
                    {
                        string an, av;

                        reader.MoveToAttribute("name");
                        an = reader.Value;
                        reader.MoveToAttribute("value");
                        av = reader.Value;
                        //reader.MoveToAttribute("type");

                        rd.Add(an, av);
                    }
                    break;

                case XmlNodeType.EndElement:
                    IsNotEnd = false;
                    break;

                case XmlNodeType.Text:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.XmlDeclaration:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.ProcessingInstruction:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.Comment:
                    reader.ReadOuterXml();
                    break;

                case XmlNodeType.Attribute:
                    reader.Read();
                    break;

                case XmlNodeType.Whitespace:
                    reader.Read();
                    break;
                }
            }

            return(rd);
        }
Пример #32
0
 public void Load(XmlReader reader)
 {
     reader.Read();
     this.SettingsTree = reader.ReadOuterXml();
 }
Пример #33
0
Файл: test.cs Проект: mono/gert
	void IXmlSerializable.ReadXml (XmlReader reader)
	{
		XmlDocument doc = new XmlDocument ();
		string str = reader.ReadString ();
		try {
			doc.LoadXml (str);
		} catch {
			doc.LoadXml (reader.ReadOuterXml ());
		}
		mFuncXmlNode = (XmlNode) (doc.DocumentElement);
	}