示例#1
1
        private static void FixNuSpec(ProjectVersion version, string file)
        {
            XNamespace ns = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd";
            var readerSettings = new XmlReaderSettings
            {
                IgnoreComments = false,
                IgnoreWhitespace = false         
            };
            XDocument doc;
            using (var reader = XmlReader.Create(file, readerSettings))
            {
                doc = XDocument.Load(reader);
            }
            var versionElement = doc.Descendants(ns + "version").Single();
            versionElement.Value = version.FullText;
            var dependency = doc.Descendants(ns + "dependency").Where(x => (string)x.Attribute("id") == "NodaTime").FirstOrDefault();
            if (dependency != null)
            {
                dependency.SetAttributeValue("version", version.Dependency);
            }

            var writerSettings = new XmlWriterSettings
            {
                Encoding = new UTF8Encoding(false),
                Indent = false,
                NewLineHandling = NewLineHandling.None,
            };

            using (var writer = XmlWriter.Create(file, writerSettings))
            {
                doc.Save(writer);
            }
        }
        private static IEnumerable<StorageAccountAdapter> LoadFromXml()
        {
            List<StorageAccountAdapter> accounts = new List<StorageAccountAdapter>();

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;

            using (XmlReader reader = XmlReader.Create("accounts.xml"))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);

                var nodes = doc.DocumentElement.SelectNodes("/accounts/account").OfType<XmlNode>().ToList();
                foreach (XmlNode node in nodes)
                {
                    StorageAccountAdapter adapter = CreateAccount(node);
                    if (adapter != null)
                    {
                        accounts.Add(adapter);
                    }
                }
            }

            return accounts.OrderBy(f => f.Name);
        }
示例#3
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // Skip XML Dtd processing
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.DtdProcessing = 0;
            // Read in TMX level
            StreamReader stream = System.IO.File.OpenText("Content/Maps/Level.tmx");
            // Create XmlReader based on level stream
            XmlReader reader = XmlReader.Create(stream, settings);
            // Initialize engine with level xml
            engine = new Engine.Engine(this, reader);
            // Add engine to components
            Components.Add(engine);
            // Disable engine (Titlescreen is startup screen)
            engine.Visible = false;
            engine.Enabled = false;
            // Add engine to services
            Services.AddService(typeof(Engine.Engine), engine);

            // Add InputManager (Keyboard, GamePad)
            Components.Add(new InputManager(this));

            // Add titlescreen
            titleScreen = new TitleScreen(this);
            Components.Add(titleScreen);

            // Add ControlManager
            controlManager = new ControlManager(this);
            Components.Add(controlManager);
            Services.AddService(typeof(ControlManager), controlManager);

            base.Initialize();
        }
示例#4
0
        public void PairNodes(Node node1, Node node2)
        {
            try
            {
                XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
                xmlReaderSettings.IgnoreWhitespace = true;
                xmlReaderSettings.IgnoreComments = true;

                //if (!File.Exists(XmlFilePath)) return;
                var document = new XmlDocument();
                document.Load(XmlFilePath);

                var xmlElementList = document.GetElementsByTagName("NodePairs");
                var newXmlElement = document.CreateElement("NodePair");
                var firstNode = document.CreateElement("Node");
                var secondNode = document.CreateElement("Node");
                firstNode.SetAttribute("Id", node1.Id);
                secondNode.SetAttribute("Id", node2.Id);
                newXmlElement.AppendChild(firstNode);
                newXmlElement.AppendChild(secondNode);
                xmlElementList[0].AppendChild(newXmlElement);
                document.Save(XmlFilePath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
示例#5
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="xml">XML to validate</param>
        /// <param name="schemaUri">Schema Uri</param>
        public DnaXmlValidator(string xml, string schemaUri)
        {
            _schemaUri = schemaUri;
            // set up the schema
            LoadSchema(schemaUri);

            // set up the xml reader
            _rawXml = xml;
            _xml = new StringReader(xml);

            // set up the settings for validating the xml
            _validationSettings = new XmlReaderSettings();
            _validationSettings.Schemas.Add(_xmlSchema);
            _validationSettings.IgnoreWhitespace = true;
            _validationSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
            _validationSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            _validationSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
            _validationSettings.ValidationType = ValidationType.Schema;
            try
            {
                _validationSettings.Schemas.Compile();
            }
            catch (XmlSchemaException e)
            {
                string s = e.SourceUri;
            }
            _validationSettings.ValidationEventHandler += new ValidationEventHandler(xmlReaderSettingsValidationEventHandler);
            _validationSettings.DtdProcessing = DtdProcessing.Parse;
            // set the the XmlReader for validation
            _validator = XmlReader.Create(_xml, _validationSettings);
        }
示例#6
0
        /// <summary>
        /// Initializes internal properties
        /// </summary>
        private void InitializeReader()
        {
            Sys.XmlReaderSettings xmlReaderSettings = new Sys.XmlReaderSettings();
            xmlReaderSettings.IgnoreComments = true;
            xmlReaderSettings.IgnoreProcessingInstructions = true;
            xmlReaderSettings.IgnoreWhitespace             = true;

            _xmlReader = Sys.XmlReader.Create(_input, xmlReaderSettings);

            _xmlReader.Read();
            while (_xmlReader.EOF == false && _insideOsm == false)
            {
                switch (_xmlReader.NodeType)
                {
                case Sys.XmlNodeType.Element:
                    if (_xmlReader.Name != "osm")
                    {
                        throw new Sys.XmlException("Invalid xml root element. Expected <osm>.");
                    }

                    _insideOsm = true;
                    break;

                default:
                    _xmlReader.Read();
                    break;
                }
            }
        }
示例#7
0
        /// <summary>
        /// Reads the PAP message from the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public static PapMessage Read(Stream stream)
        {
            XmlReaderSettings settings =
                new XmlReaderSettings
                {
                    CheckCharacters = true,
                    CloseInput = true,
                    ConformanceLevel = System.Xml.ConformanceLevel.Document,
                    DtdProcessing = DtdProcessing.Parse,
                    IgnoreComments = true,
                    ValidationType = ValidationType.DTD
                };
            XmlReader reader = XmlReader.Create(stream, settings);
            try
            {
                // Deserialize the data
                XmlSerializer serializer = new XmlSerializer(typeof(PapRoot));
                object resultRoot = serializer.Deserialize(reader);

                // Extract the response object from the appropriate root
                PapMessage response = null;
                if (resultRoot is PapRoot)
                {
                    response = ((PapRoot)resultRoot).Response;
                }

                return response;
            }
            finally
            {
                reader.Close();
            }
        }
示例#8
0
文件: test.cs 项目: mono/gert
	static void Main ()
	{
		string dir = AppDomain.CurrentDomain.BaseDirectory;

		XmlTextReader xtr = new XmlTextReader (Path.Combine (dir, "MyTestService.wsdl"));

#if NET_2_0
		XmlReaderSettings settings = new XmlReaderSettings ();
		settings.ValidationType = ValidationType.Schema;
		settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/", "http://schemas.xmlsoap.org/wsdl/");
		settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/http/", "http://schemas.xmlsoap.org/wsdl/http/");
		settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/soap/", "http://schemas.xmlsoap.org/wsdl/soap/");
		settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/soap12/", "http://schemas.xmlsoap.org/wsdl/soap12/wsdl11soap12.xsd");

		XmlReader vr = XmlReader.Create (xtr, settings);
#else
		XmlValidatingReader vr = new XmlValidatingReader (xtr);
		vr.ValidationType = ValidationType.Schema;
		vr.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/", "http://schemas.xmlsoap.org/wsdl/");
		vr.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/http/", "http://schemas.xmlsoap.org/wsdl/http/");
		vr.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/soap/", "http://schemas.xmlsoap.org/wsdl/soap/");
#endif

		while (vr.Read ()) {
		}
		
	}
 private static XmlReaderSettings CreateXmlReaderSettings(XmlSchema xmlSchema)
 {
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.ValidationType = ValidationType.Schema;
     settings.Schemas.Add(xmlSchema);
     return settings;
 }
示例#10
0
        public static bool IsXmlValid(string schemaFile, string xmlFile)
        {
            try
            {
                var valid = true;
                var sc = new XmlSchemaSet();
                sc.Add(string.Empty, schemaFile);
                var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = sc };
                settings.ValidationEventHandler += delegate { valid = false; };
                settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.IgnoreWhitespace = true;
                var reader = XmlReader.Create(xmlFile, settings);

                try
                {
                    while (reader.Read()) {}
                }
                catch (XmlException xmlException)
                {
                    Console.WriteLine(xmlException);
                }
                return valid;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// Reads data from a stream
        /// </summary>
        /// <param name="stream">The stram to read data from</param>
        public void Read(Stream stream)
        {
            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
            xmlReaderSettings.IgnoreComments = true;
            xmlReaderSettings.IgnoreProcessingInstructions = true;
            xmlReaderSettings.IgnoreWhitespace = true;

            try {
                _xmlReader = XmlTextReader.Create(stream, xmlReaderSettings);

                _xmlReader.Read();
                while (false == _xmlReader.EOF) {

                    switch (_xmlReader.NodeType) {
                        case XmlNodeType.XmlDeclaration:
                            _xmlReader.Read();
                            continue;

                        case XmlNodeType.Element:
                            if (_xmlReader.Name != "gpx")
                                throw new XmlException("Invalid xml root element. Expected <gpx>.");

                            ReadGPXTag();
                            return;

                        default:
                            throw new XmlException();
                    }
                }
            }
            finally {
                _xmlReader.Close();
                _xmlReader = null;
            }
        }
示例#12
0
        /// <summary>
        /// Loads the WorldMarket data from text source.
        /// </summary>
        /// <param name="xmlText">The UTF-8 text source.</param>
        public static WorldMarket LoadTextSource(string xmlText)
        {
            try
            {
                XmlReaderSettings readerSettings = new XmlReaderSettings();
#if !(NETFX_CORE || SILVERLIGHT)
                XmlSchema sch = XmlSchema.Read(new System.IO.StringReader(Properties.Resources.market_schema), null);
                readerSettings.Schemas.Add(sch);
                readerSettings.ValidationType = ValidationType.Schema;
#endif
                XmlReader market = XmlReader.Create(new System.IO.StringReader(xmlText), readerSettings);
                XmlSerializer ser = new XmlSerializer(typeof(System.Resources.WorldMarket));

                System.Resources.WorldMarket wm = (System.Resources.WorldMarket)ser.Deserialize(market);

                WorldMarket result = new WorldMarket();

                foreach (var s in wm.Sectors) { result.mSectors.Add(new Sector(s)); }
                foreach (var s in wm.Industries) { result.mIndustries.Add(new Industry(s, result)); }
                foreach (var s in wm.Currencies) { result.mCurrencies.Add(new CurrencyInfo(s)); }
                foreach (var s in wm.Countries) { result.mCountries.Add(new CountryInfo(s, result)); }
                foreach (var s in wm.StockExchanges) { result.mStockExchanges.Add(new StockExchange(s, result)); }
                foreach (var s in wm.Indices) { result.mIndices.Add(new YID(s, result)); }
                foreach (var s in wm.FundCategories) { result.mFundCategories.Add(new FundCategory(s)); }
                foreach (var s in wm.FundFamilies) { result.mFundFamilies.Add(new FundFamily(s)); }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("The XML text is not valid. See InnerException for more details.", ex);
            }
        }
        private void LoadRuleFile()
        {
            if (string.IsNullOrEmpty(_fileName))
            {
                throw new NullReferenceException("Please set file name first");
            }
            if (!File.Exists(_fileName))
            {
                throw new Exception(string.Format("File {0} does not exists on disk",Path.GetFullPath(_fileName)));
            }

            using (Stream stream = File.OpenRead(_fileName))
            {
                var settings = new XmlReaderSettings
                {
                    ValidationType = ValidationType.Schema,
                };
                using (XmlReader reader = XmlReader.Create(stream, settings))
                {
                    XDocument fileDocument = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
                    LoadRulesData(fileDocument);
                    reader.Close();
                }
                stream.Close();
            }
        }
		public static bool TryGetSimpleRulesFromCollationNode(string collationXml, out string rules)
		{
			if (collationXml == null)
			{
				throw new ArgumentNullException("collationXml");
			}

			XmlReaderSettings readerSettings = new XmlReaderSettings();
			readerSettings.CloseInput = true;
			readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
			readerSettings.IgnoreWhitespace = true;
			rules = null;
			using (XmlReader collationReader = XmlReader.Create(new StringReader(collationXml), readerSettings))
			{
				// simple rules can't deal with any non-default settings
				if (XmlHelpersV0.FindNextElementInSequence(collationReader, "settings", LdmlNodeComparer.CompareElementNames))
				{
					return false;
				}
				if (!XmlHelpersV0.FindNextElementInSequence(collationReader, "rules", LdmlNodeComparer.CompareElementNames))
				{
					rules = string.Empty;
					return true;
				}
				rules = GetSimpleRulesFromRulesNode(collationReader);
			}
			return rules != null;
		}
示例#15
0
        private static byte[] ReadXml(Stream data)
        {
            data.Position = 0;

            var settings = new XmlReaderSettings
            {
                CloseInput = false,
                IgnoreComments = true,
                IgnoreWhitespace = true,
                IgnoreProcessingInstructions = true,
            };

            using (var reader = XmlReader.Create(data, settings))
            {
                try
                {
                    if (!reader.ReadToFollowing("KeyFile"))
                        return null;

                    if (!reader.ReadToDescendant("Key"))
                        return null;

                    if (!reader.ReadToDescendant("Data"))
                        return null;

                    var base64 = reader.ReadElementContentAsString();
                    return Convert.FromBase64String(base64);
                }
                catch (XmlException)
                {
                    return null;
                }
            }
        }
        public static XmlReader ReadAsXmlReader(this HttpContent content, XmlReaderSettings settings)
        {
            FX.ThrowIfNull(content, "content");
            FX.ThrowIfNull(content, "settings");

            return XmlReader.Create(content.ContentReadStream, settings);
        }
示例#17
0
        public bool Validate()
        {
            is_success_ = false;

            XmlDocument document = new XmlDocument();
            document.Load(xml_filename_);

            XmlReaderSettings setting = new XmlReaderSettings();
            setting.CloseInput = true;
            setting.ValidationEventHandler += Handler;
            setting.ValidationType = ValidationType.Schema;
            setting.Schemas.Add(null, xsd_filename_);
            setting.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings |
                                      XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                      XmlSchemaValidationFlags.ProcessInlineSchema |
                                      XmlSchemaValidationFlags.ProcessSchemaLocation;

            is_success_ = true;

            using (XmlReader validationReader = XmlReader.Create(xml_filename_, setting))
            {
                while (validationReader.Read())
                {
                    /* do nothing for while */
                }
            }

            return is_success_;
        }
示例#18
0
        ///////////////////////////////////////////////////////////////////////
        protected override WeatherData FetchCurrentWeather(String location)
        {
            Settings conf = Settings.Default;

            // build the URL for the weather service API
            StringBuilder url = new StringBuilder();
            url.Append("http://weather.yahooapis.com/forecastrss?");
            url.Append("u=c&w=").Append(conf.Location);  // WOEID
            _logger.Debug("Fetch: {0}", url.ToString());

            XmlReaderSettings sett = new XmlReaderSettings();
            sett.IgnoreWhitespace = true;
            sett.IgnoreComments = true;

            WeatherData data = new WeatherData {
                Location = location,
                LastUpdated = DateTime.Now,
            };

            XmlReader reader = XmlReader.Create(url.ToString(), sett);
            while (reader.Read()) {
                if (reader.Name == "lastBuildDate") {
                    // TODO make this work...
                    //data.LastUpdated = reader.ReadElementContentAsDateTime();
                }

                if (reader.Name == "yweather:location") {
                    data.Name = reader["city"];
                }

                if (reader.Name == "yweather:condition") {
                    data.Temperature = int.Parse(reader["temp"]);
                }

                // FIXME this should look at tomorrow if the sunrise or sunset are old
                if (reader.Name == "yweather:astronomy") {
                    data.Sunrise = DateTime.Parse(reader["sunrise"]);
                    data.Sunset = DateTime.Parse(reader["sunset"]);
                }

                if (reader.Name == "yweather:atmosphere") {
                    data.Humidity = int.Parse(reader["humidity"]);
                    data.Pressure = decimal.Parse(reader["pressure"]);
                }

                if (reader.Name == "yweather:wind") {
                    data.WindSpeed = (int) decimal.Parse(reader["speed"]);
                }

                if (reader.Name == "geo:lat") {
                    data.Latitude = reader.ReadElementContentAsDecimal();
                }

                if (reader.Name == "geo:long") {
                    data.Longitude = reader.ReadElementContentAsDecimal();
                }
            }

            return data;
        }
示例#19
0
        private XmlReader CreateXmlReader()
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;

            return XmlTextReader.Create(_fs, settings);
        }
示例#20
0
		public void XmlResolver ()
		{
			XmlReaderSettings xrs = new XmlReaderSettings ();
			// setter-only property
			xrs.XmlResolver = new ConcreteXmlResolver ();
			xrs.XmlResolver = null;
		}
        protected void btnDisplay_Click(object sender, EventArgs e)
        {
            //XML文件所在位置
            string xmlFilePath = Server.MapPath(@"Docs\Book1.xml");

            //创建XmlReaderSettings对象,并设置适合的属性
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, Server.MapPath(@"Docs\Book.xsd"));
            settings.IgnoreWhitespace = false;

            try
            {
                //引用XMLReader对象,并指定设置
                XmlReader reader = XmlReader.Create(xmlFilePath, settings);

                while (reader.Read())
                {
                    Response.Write(reader.Value + "<br/>");
                }
            }
            catch (Exception ex)
            {
                Response.Write("An Exception: " + ex.Message);
            }
        }
示例#22
0
        private static Script LoadScript(string fileName)
        {
            try
            {
                var settings = new XmlReaderSettings();

                string resourceName = typeof(ScriptLoader).Namespace + ".Script-v1.xsd";

                using (var stream = typeof(ScriptLoader).Assembly.GetManifestResourceStream(resourceName))
                using (var reader = XmlReader.Create(stream))
                {
                    settings.Schemas.Add(Constants.ScriptNs, reader);
                }

                settings.ValidationType = ValidationType.Schema;

                using (var reader = XmlReader.Create(fileName, settings))
                {
                    var serializer = new XmlSerializer(typeof(Script));

                    return (Script)serializer.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                throw new ScriptException(UILabels.InvalidScript, ex);
            }
        }
        public void SerializeAndDeserializeSqlTestConfiguration()
        {
            StringBuilder output = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            using (XmlWriter writer = XmlWriter.Create(output, settings))
            {
                // Add a testObject and serialize it the configuration section
                configSection.Value = 20;
                configSection.WriteXml(writer);

                Assert.IsNotNull(writer);

                writer.Close();
                Assert.IsTrue(output.Length > 0);
                writer.Flush();
            }

            DummySection configSection2 = new DummySection();
            XmlReaderSettings settings2 = new XmlReaderSettings();
            StringReader input = new StringReader(output.ToString());
            using (XmlReader reader = XmlReader.Create(input, settings2))
            {
                //deserialize the configuration section
                configSection2.ReadXml(reader);

                Assert.AreEqual(configSection2.Value, configSection.Value);
            }
        }
        /// <summary> Validates a single METS XML file </summary>
        /// <param name="METS_File"> Location and name of file to validate </param>
        /// <returns> TRUE if it validates, otherwise FALSE </returns>
        /// <remarks> If this does not validate, the accumulated errors can be reached through the 'Errors' property. </remarks>
        public bool Validate_Against_Schema(string METS_File)
        {
            try
            {
                // Set some initial values
                isValid = true;
                errors = new StringBuilder();

                // Create the reader and validator
                XmlReaderSettings metsSettings = new XmlReaderSettings();
                metsSettings.Schemas.Add(cache);
                metsSettings.ValidationType = ValidationType.Schema;
                metsSettings.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);

                XmlReader validator = XmlReader.Create(METS_File, metsSettings);

                // Step through the XML file
                while (validator.Read())
                {
                    /* Just reading through, looking for problems... */
                }
                validator.Close();

                // Return the valid flag
                return isValid;
            }
            catch
            {
                errors.Append("UNSPECIFIED ERROR CAUGHT DURING VALIDATION");
                return false;
            }
        }
        public void when_reading_topic_settings_then_sets_default_value_from_schema()
        {
            // Setup XSD validation so that we can load an XDocument with PSVI information
            var schema = XmlSchema.Read(typeof(InfrastructureSettings).Assembly.GetManifestResourceStream("Infrastructure.Azure.Settings.xsd"), null);
            var readerSettings = new XmlReaderSettings { ValidationType = ValidationType.Schema };
            readerSettings.Schemas.Add(schema);
            readerSettings.Schemas.Compile();

            using (var reader = XmlReader.Create("Settings.Template.xml", readerSettings))
            {
                var doc = XDocument.Load(reader);
                // Even if the attribute is not in the XML file, we can access the 
                // attribute because the XSD validation is adding the default value 
                // post validation.
                var defaultValue = doc.Root.Descendants(
                    XNamespace.Get(InfrastructureSettings.XmlNamespace) + "Topic")
                    .Skip(1)
                    .First()
                    .Attribute("DuplicateDetectionHistoryTimeWindow")
                    .Value;

                var settings = InfrastructureSettings.Read("Settings.Template.xml").ServiceBus;

                Assert.Equal(
                    TimeSpan.Parse(defaultValue),
                    settings.Topics[1].DuplicateDetectionHistoryTimeWindow);
            }
        }
        private void StartupLoad()
        {
            // Init class properties
            SearchTypes = new List<string>();

            // Load stuff
            XmlReaderSettings settingsReaderSettings = new XmlReaderSettings();
            settingsReaderSettings.ValidationType = ValidationType.Schema;
            try
            {
                settingsReaderSettings.Schemas.Add("http://www.w3.org/2001/XMLSchema", "SettingsSchema.xsd");
            }
            catch (System.IO.IOException e)
            {
                ErrorDialogs.DetailedError("IO Exception", "Unable to read critical config file SettingsSchema.xsd.", e.Message);
                throw;
            }

            // Settings
            XmlReader settingsFileReader;
            try
            {
                settingsFileReader = XmlReader.Create("Settings.xml", settingsReaderSettings);
            }
            catch (System.IO.IOException e)
            {
                ErrorDialogs.DetailedError("IO Exception", "Unable to read critical config file Settings.xml.", e.Message);
                throw;
            }
            settingsFileReader.MoveToContent();
            settingsFileReader.ReadToFollowing("SearchType");
            SearchTypes.Add(settingsFileReader.GetAttribute("Name"));
            settingsFileReader.Close();
        }
示例#27
0
        private string ToHtml()
        {
            if (Services.StrandsCache.Contains(this))
            {
                return Services.StrandsCache.Read(this);
            }
            else
            {
                var transform = new XslCompiledTransform(true);
                var arguments = new XsltArgumentList();
                var settings = new XsltSettings();
                var readersettings = new XmlReaderSettings();
                //string xslsrc = (!string.IsNullOrEmpty(this.DisplayType)) ? "/XMLList.xsl" : "/Strands.xsl";
                //var xslfile = (this.Name == "themes") ? HttpContext.Current.Server.MapPath(this._xslAppUrl + "/StrandList.xsl") : HttpContext.Current.Server.MapPath(this._xslAppUrl + xslsrc);
                var xslfile = HttpContext.Current.Server.MapPath(this._xslAppUrl + ((!string.IsNullOrEmpty(this.DisplayType)) ? "XMLList.xsl" : this.XslName));

                settings.EnableDocumentFunction = true;
                settings.EnableScript = true;
                readersettings.DtdProcessing = DtdProcessing.Parse;
                readersettings.ValidationType = ValidationType.None;
                transform.Load(xslfile, settings, new XmlUrlResolver());
                arguments = TransformArguments(this);
                using (XmlReader reader = XmlReader.Create(this.GetDirectoryPath(), readersettings))
                {
                    System.IO.StringWriter writer = new System.IO.StringWriter();

                    transform.Transform(reader, arguments, writer);
                    return Services.StrandsCache.Write(this, writer.ToString());
                }
            }
        }
示例#28
0
		private static XmlReader CreateXmlReaderFromStream(Stream configStream) {
			var readerSettings = new XmlReaderSettings();
			var xtr = new XmlTextReader(configStream);
			readerSettings.ValidationType = ValidationType.None;
			xtr.EntityHandling = EntityHandling.ExpandEntities;
			return XmlReader.Create(xtr, readerSettings);
		}
示例#29
0
 static Book[] XmlDocumentDeserializer(string path)
 {
     XmlDocument doc = new XmlDocument();
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.IgnoreComments = true;
     XmlReader reader = XmlReader.Create(path, settings);
     doc.Load(reader);
     if(doc == null)
     {
         return null;
     }
     List<Book> bookList = new List<Book>();
     XmlNode xn = doc.SelectSingleNode("bookstore");
     XmlNodeList xnl = xn.ChildNodes;
     foreach(XmlNode _xn in xnl)
     {
         Book book = new Book();
         XmlElement xe = (XmlElement)_xn;
         book.Type = xe.GetAttribute("Type").ToString();
         book.ISBN = xe.GetAttribute("ISBN").ToString();
         XmlNodeList _xnl = xe.ChildNodes;
         book.Name = _xnl.Item(0).InnerText;
         book.Author = _xnl.Item(1).InnerText;
         float price;
         if(float.TryParse(_xnl.Item(2).InnerText,out price))
         {
             book.Price = price;
         }
         bookList.Add(book);
     }
     return bookList.ToArray();
 }
示例#30
0
        //read XML file for patent info
        public static SortedList<int, Patent> GetPatents()
        {
            XmlDocument doc = new XmlDocument();

            //if file doesn't exist, create it
            if (!File.Exists("Patents.xml"))
                doc.Save("Patents.xml");

            SortedList<int, Patent> patents = new SortedList<int, Patent>();

            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.IgnoreWhitespace = true;
            readerSettings.IgnoreComments = true;

            XmlReader readXml = null;

            try
            {
                readXml = XmlReader.Create(path, readerSettings);

                if (readXml.ReadToDescendant("Patent")) //read to first Patent node
                {
                    do
                    {
                        Patent patent = new Patent();
                        patent.Number = Convert.ToInt32(readXml["Number"]);
                        readXml.ReadStartElement("Patent");
                        patent.AppNumber = readXml.ReadElementContentAsString();
                        patent.Description = readXml.ReadElementContentAsString();
                        patent.FilingDate = DateTime.Parse(readXml.ReadElementContentAsString());
                        patent.Inventor = readXml.ReadElementContentAsString();
                        patent.Inventor2 = readXml.ReadElementContentAsString();

                        int key = patent.Number; //assign key to value

                        patents.Add(key, patent); //add key-value pair to list
                    }
                    while (readXml.ReadToNextSibling("Patent"));
                }
            }
            catch (XmlException ex)
            {
                MessageBox.Show(ex.Message, "Xml Error");
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message, "IO Exception");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception Occurred");
            }
            finally
            {
                if (readXml != null)
                    readXml.Close();
            }

            return patents;
        }
示例#31
0
        public bool ValidateXmlFile()
        {
            XmlReader rdr;
            rdr = null;

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(null, schemaFileName);
                settings.ValidationEventHandler += ValidationFailed;
                rdr = XmlReader.Create(xmlFileName, settings);

                while (rdr.Read())
                {
                    //spool text to output device
                }
                return failed;
            }
            catch
            {
                throw new Exception("Validating of xml failed");
            }
            finally
            {
                // close the reader
                if (rdr != null)
                {
                    rdr.Close();
                }
            }
        }
示例#32
0
        /// <summary>
        /// コンフィグファイルの読み込み
        /// </summary>
        /// <returns>読み込んだファイルのインスタンスを返す</returns>
        public static APPConfig Read()
        {
            APPConfig loadAry;

            if (!System.IO.File.Exists(m_fileName))
            {
                loadAry = new APPConfig();
                loadAry.Save();
            }
            else
            {
                try
                {
                    // デシリアライズする
                    var serializer  = new XmlSerializer(typeof(APPConfig));
                    var xmlSettings = new System.Xml.XmlReaderSettings()
                    {
                        CheckCharacters = false,
                    };
                    using (var sr = new StreamReader(m_fileName, Encoding.UTF8))
                        using (var xmlReader = XmlReader.Create(sr, xmlSettings))
                        {
                            loadAry = (APPConfig)serializer.Deserialize(xmlReader);
                            xmlReader.Close();
                        }
                    // エディター関連の
                    foreach (var v in loadAry.FontAndColors)
                    {
                        foreach (var w in v.Value.PrintSettings)
                        {
                            if (w.Key == "TextEditor")
                            {
                                w.Value.ReadXmlTextEditorAfterCommit(v.Value.Theme);
                            }
                            else if (w.Key == "OutputWindow")
                            {
                                w.Value.ReadXmlOutputWindowAfterCommit(v.Value.Theme);
                            }
                            else if (w.Key == "SearchResultWindow")
                            {
                                w.Value.ReadXmlSearchResultWindowAfterCommit(v.Value.Theme);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    loadAry = new APPConfig();
                    loadAry.Save();
                    Console.WriteLine(e.Message);
                }
            }


            return(loadAry);
        }
示例#33
0
        public avm.Component DeserializeAvmComponentXml_NonStatic(TextReader reader)
        {
            System.Xml.XmlReaderSettings xmlReaderSettings = new System.Xml.XmlReaderSettings();
            xmlReaderSettings.IgnoreWhitespace = true;

            System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(reader, xmlReaderSettings);

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Component), OpenMETA.Interchange.AvmXmlSerializer.getAVMClasses());
            serializer.UnknownElement += new XmlElementEventHandler(DeSerializer_UnknownElement);
            avm.Component ac_import = (avm.Component)serializer.Deserialize(xmlReader);
            return(ac_import);
        }
示例#34
0
        public static XDocument StringToXDocument(string input, XmlResolver resolver)
        {
            Encapsulation.TryValidateParam(input, nameof(input));

            var options = new System.Xml.XmlReaderSettings {
                DtdProcessing = DtdProcessing.Prohibit, XmlResolver = resolver
            };

            using (var reader = XmlReader.Create(new StringReader(input), options))
            {
                return(XDocument.Load(reader));
            }
        }
示例#35
0
 public PmlXmlReader(BinaryReader Reader)
 {
     pReader      = Reader;
     pXMLSettings = new System.Xml.XmlReaderSettings();
     pXMLSettings.ConformanceLevel             = System.Xml.ConformanceLevel.Document;
     pXMLSettings.CloseInput                   = true;
     pXMLSettings.IgnoreComments               = true;
     pXMLSettings.IgnoreProcessingInstructions = true;
     pXMLSettings.IgnoreWhitespace             = true;
     pXMLSettings.ValidationType               = System.Xml.ValidationType.None;
     pXMLSettings.ValidationFlags              = System.Xml.Schema.XmlSchemaValidationFlags.None;
     pXMLSettings.CheckCharacters              = true;
 }
示例#36
0
        private static bool EsCFDIXmlValido(List <String> PathsXSD, System.IO.StringReader XMLPath, out List <string> Errores)
        {
            try
            {
                // 0- Initialize variables...
                _IsValid  = true;
                Resultado = new List <string>();


                // 1- Read XML file content
                Reader = new System.Xml.XmlTextReader(XMLPath);

                // 3- Create a new instance of XmlSchema object
                System.Xml.Schema.XmlSchema  Schema         = new System.Xml.Schema.XmlSchema();
                System.Xml.XmlReaderSettings ReaderSettings = new System.Xml.XmlReaderSettings();

                // 2- Read Schema file content
                foreach (String XSD in PathsXSD)
                {
                    StreamReader SR = new StreamReader(XSD);
                    Schema = System.Xml.Schema.XmlSchema.Read(SR, new System.Xml.Schema.ValidationEventHandler(ReaderSettings_ValidationEventHandler));
                    ReaderSettings.ValidationType = System.Xml.ValidationType.Schema;
                    ReaderSettings.Schemas.Add(Schema);
                }
                // 8- Add your ValidationEventHandler address to
                // XmlReaderSettings ValidationEventHandler
                ReaderSettings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ReaderSettings_ValidationEventHandler);

                // 9- Create a new instance of XmlReader object
                System.Xml.XmlReader objXmlReader = System.Xml.XmlReader.Create(Reader, ReaderSettings);

                // 10- Read XML content in a loop
                while (objXmlReader.Read())
                {
                    // empty loop
                }

                // Se cierra el validador
                objXmlReader.Close();
                Errores = Resultado;
                return(_IsValid);
            }
            catch (Exception ex)
            {
                Errores = new List <string>();
                Errores.Add("Error de validacion del XML Error:" + ex.ToString());
                return(true);
            }
        }
示例#37
0
        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
        {
            writer.WriteStartElement("XMLSerializer");

            string xml = WriteObject(graph);

            using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml)))
            {
                var settings = new System.Xml.XmlReaderSettings();
                settings.IgnoreWhitespace = true;
                var w = XmlDictionaryReader.Create(ms, settings);
                writer.WriteNode(w, true);
            }

            writer.WriteEndElement();
        }
示例#38
0
        private static void ApplyTransform(string inputFile, string outputFile, string transform)
        {
            var myXslTrans = new System.Xml.Xsl.XslCompiledTransform();

            System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
            //send transform to handle the DTD
            settings.DtdProcessing = DtdProcessing.Parse;

            //load the xslt tranform file
            myXslTrans.Load(transform);

            //tranforming file
            var input  = XmlReader.Create(inputFile, settings);
            var writer = XmlWriter.Create(outputFile);

            myXslTrans.Transform(input, writer);
            input.Dispose();
            writer.Dispose();
        }
示例#39
0
      public override XmlNode GetMetaData(XmlDocument oDoc)
      {
          XmlDocument       responseDoc = new XmlDocument();
          XmlReaderSettings oSettings   = new System.Xml.XmlReaderSettings();

          oSettings.IgnoreWhitespace = true;
          oSettings.ProhibitDtd      = false;
          oSettings.XmlResolver      = null;
          oSettings.ValidationType   = ValidationType.None;
          using (XmlReader oResponseXmlStream = XmlReader.Create(m_strCapabilitiesFilePath, oSettings))
          {
              responseDoc.Load(oResponseXmlStream);
          }
          XmlNode oNode   = responseDoc.DocumentElement;
          XmlNode newNode = oDoc.CreateElement(oNode.Name);

          newNode.InnerXml = oNode.InnerXml;
          return(newNode);
      }
示例#40
0
文件: Util.cs 项目: wooln/AK47Source
        public static XmlReaderSettings GetDraftingLinkXmlReaderSettings()
        {
            var readerSettings = CategoryLinkAdapter.Settings;

            if (readerSettings == null)
            {
                readerSettings = new System.Xml.XmlReaderSettings()
                {
                    IgnoreWhitespace = true,
                    IgnoreComments   = true,
                };

                var schemaDoc = WebXmlDocumentCache.GetDocument("~/App_Data/CategorySchema.xsd");

                var schema = XmlSchema.Read(new StringReader(schemaDoc), null);
                CategoryLinkAdapter.Settings = readerSettings;
            }

            return(readerSettings);
        }
        /// <summary>
        /// validates the given XML content and stores the results in the <paramref name="recs"/>.
        /// </summary>
        /// <param name="recs">Validation records</param>
        /// <param name="xmlContent">Content to be validated</param>
        public void Validate(AasValidationRecordList recs, Stream xmlContent)
        {
            if (recs == null)
            {
                throw new ArgumentException($"Unexpected null {nameof(recs)}");
            }

            if (xmlContent == null)
            {
                throw new ArgumentException($"Unexpected null {nameof(xmlContent)}");
            }

            // load/ validate on same records
            var settings = new System.Xml.XmlReaderSettings();

            settings.ValidationType = System.Xml.ValidationType.Schema;
            settings.Schemas        = xmlSchemaSet;

            settings.ValidationEventHandler +=
                (object sender, System.Xml.Schema.ValidationEventArgs e) =>
            {
                recs.Add(
                    new AasValidationRecord(
                        AasValidationSeverity.Serialization, null,
                        $"XML: {e?.Exception?.LineNumber}, {e?.Exception?.LinePosition}: {e?.Message}"));
            };

            // use the xml stream
            using (var reader = System.Xml.XmlReader.Create(xmlContent, settings))
            {
                while (reader.Read())
                {
                    // Invoke callbacks
                }
                ;
            }
        }
示例#42
0
        /// <summary>
        /// Synchronous HTTP download
        /// </summary>
        protected virtual void Download()
        {
            Debug.Assert(Url.StartsWith("http://"));
            DownloadStartTime = DateTime.Now;
            try
            {
                try
                {
                    // If a registered progress-callback, inform it of our download progress so far.
                    OnProgressCallback(0, -1);
                    OnDebugCallback(this);

                    // check to see if thread was aborted (multiple such checks within the thread function)
                    if (stopFlag)
                    {
                        IsComplete = true;
                        return;
                    }

                    // create content stream from memory or file
                    if (isMemoryDownload && ContentStream == null)
                    {
                        ContentStream = new MemoryStream();
                    }
                    else
                    {
                        // Download to file
                        string targetDirectory = Path.GetDirectoryName(SavedFilePath);
                        if (targetDirectory.Length > 0)
                        {
                            Directory.CreateDirectory(targetDirectory);
                        }
                        ContentStream = new FileStream(SavedFilePath, FileMode.Create);
                    }

                    // Create the request object.
                    request           = (HttpWebRequest)WebRequest.Create(Url);
                    request.UserAgent = UserAgent;

                    if (stopFlag)
                    {
                        IsComplete = true;
                        return;
                    }

                    request.Proxy = ProxyHelper.DetermineProxyForUrl(
                        Url,
                        useWindowsDefaultProxy,
                        useDynamicProxy,
                        proxyUrl,
                        proxyUserName,
                        proxyPassword);

                    request.ProtocolVersion = HttpVersion.Version11;


                    // TODO: probably better done via BeginGetResponse() / EndGetResponse() because this may block for a while
                    // causing warnings in thread abortion.
                    using (response = request.GetResponse() as HttpWebResponse)
                    {
                        // only if server responds 200 OK
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            if (m_bXML)
                            {
                                XmlReaderSettings oSettings = new System.Xml.XmlReaderSettings();
                                oSettings.IgnoreWhitespace = true;
                                oSettings.ProhibitDtd      = false;
                                oSettings.XmlResolver      = null;
                                oSettings.ValidationType   = ValidationType.None;
                                using (XmlReader oResponseXmlStream = XmlReader.Create(response.GetResponseStream(), oSettings))
                                {
                                    XmlDocument doc = new XmlDocument();
                                    doc.Load(oResponseXmlStream);
                                    doc.Save(ContentStream);
                                }
                            }
                            else
                            {
                                ContentType = response.ContentType;

                                // Find the data size from the headers.
                                string strContentLength = response.Headers["Content-Length"];
                                if (strContentLength != null)
                                {
                                    ContentLength = int.Parse(strContentLength, CultureInfo.InvariantCulture);
                                }

                                byte[] readBuffer = new byte[1500];
                                using (Stream responseStream = response.GetResponseStream())
                                {
                                    while (true)
                                    {
                                        //  Pass do.readBuffer to BeginRead.
                                        if (stopFlag)
                                        {
                                            IsComplete = true;
                                            return;
                                        }

                                        //  Pass do.readBuffer to BeginRead.
                                        int bytesRead = responseStream.Read(readBuffer, 0, readBuffer.Length);
                                        if (bytesRead <= 0)
                                        {
                                            break;
                                        }

                                        ContentStream.Write(readBuffer, 0, bytesRead);
                                        BytesProcessed += bytesRead;

                                        // If a registered progress-callback, inform it of our download progress so far.
                                        OnProgressCallback(BytesProcessed, ContentLength);
                                        OnDebugCallback(this);

                                        // Give up our timeslice, to allow other thread (i.e. GUI progress to respond)
                                        Thread.Sleep(0);
                                    }
                                }
                            }
                        }
                        else
                        {
                            throw new ApplicationException("BAD REQUEST");
                        }
                    }
                    HandleErrors();
                }
                catch (System.Configuration.ConfigurationException)
                {
                    // is thrown by WebRequest.Create if App.config is not in the correct format
                    // TODO: don't know what to do with it
                    throw;
                }
                catch (Exception caught)
                {
                    try
                    {
                        // Remove broken file download
                        if (ContentStream != null)
                        {
                            ContentStream.Close();
                            ContentStream = null;
                        }
                        if (SavedFilePath != null && SavedFilePath.Length > 0)
                        {
                            File.Delete(SavedFilePath);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    SaveException(caught);
                }

                if (stopFlag)
                {
                    IsComplete = true;
                    return;
                }

                if (ContentLength == 0)
                {
                    ContentLength = BytesProcessed;
                    // If a registered progress-callback, inform it of our completion
                    OnProgressCallback(BytesProcessed, ContentLength);
                }

                if (ContentStream is MemoryStream)
                {
                    ContentStream.Seek(0, SeekOrigin.Begin);
                }
                else if (ContentStream != null)
                {
                    ContentStream.Close();
                    ContentStream = null;
                }

                OnDebugCallback(this);

                if (CompleteCallback == null)
                {
                    //Verify();
#if DEBUG
                    // Used to be that it verified here, this crashes if canceled from downloads timing out (See GeoSpatialDownloadRequest.Cancel)
                    // Just notify this in debug mode for now, this may need further thought
                    // This class should only be used with CompleteCallback's anyway (there are exceptions thrown)
                    // so should be safe.
                    if (Exception != null)
                    {
                        if (Exception.InnerException != null)
                        {
                            System.Diagnostics.Debug.WriteLine("Exception in download: " + Url + "\n\t" + Exception.InnerException.Message);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("Exception in download: " + Url + "\n\t" + Exception.Message);
                        }
                    }
#endif
                }
                else
                {
                    CompleteCallback(this);
                }
            }
            catch (ThreadAbortException)
            { }
            finally
            {
                IsComplete = true;
            }
        }
示例#43
0
        internal XmlReader AddConformanceWrapper(XmlReader baseReader)
        {
            XmlReaderSettings baseReaderSettings = baseReader.Settings;
            bool          checkChars             = false;
            bool          noWhitespace           = false;
            bool          noComments             = false;
            bool          noPIs    = false;
            DtdProcessing dtdProc  = (DtdProcessing)(-1);
            bool          needWrap = false;

            if (baseReaderSettings == null)
            {
#pragma warning disable 618

#if SILVERLIGHT
                // Starting from Windows phone 8.1 (TargetsAtLeast_Desktop_V4_5_1) we converge with the desktop behavior so we'll let the reader
                // not throw exception if has different conformance level than Auto.
                if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_1)
                {
                    if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))
                    {
                        throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
                    }
                }
                else if (this.conformanceLevel != ConformanceLevel.Auto)
                {
                    throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
                }
#else
                if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))
                {
                    throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
                }
#endif

#if !SILVERLIGHT
                // get the V1 XmlTextReader ref
                XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
                if (v1XmlTextReader == null)
                {
                    XmlValidatingReader vr = baseReader as XmlValidatingReader;
                    if (vr != null)
                    {
                        v1XmlTextReader = (XmlTextReader)vr.Reader;
                    }
                }
#endif

                // assume the V1 readers already do all conformance checking;
                // wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
                if (this.ignoreWhitespace)
                {
                    WhitespaceHandling wh = WhitespaceHandling.All;
#if !SILVERLIGHT
                    // special-case our V1 readers to see if whey already filter whitespaces
                    if (v1XmlTextReader != null)
                    {
                        wh = v1XmlTextReader.WhitespaceHandling;
                    }
#endif
                    if (wh == WhitespaceHandling.All)
                    {
                        noWhitespace = true;
                        needWrap     = true;
                    }
                }
                if (this.ignoreComments)
                {
                    noComments = true;
                    needWrap   = true;
                }
                if (this.ignorePIs)
                {
                    noPIs    = true;
                    needWrap = true;
                }
                // DTD processing
                DtdProcessing baseDtdProcessing = DtdProcessing.Parse;
#if !SILVERLIGHT
                if (v1XmlTextReader != null)
                {
                    baseDtdProcessing = v1XmlTextReader.DtdProcessing;
                }
#endif
                if ((this.dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) ||
                    (this.dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse))
                {
                    dtdProc  = this.dtdProcessing;
                    needWrap = true;
                }
#pragma warning restore 618
            }
            else
            {
                if (this.conformanceLevel != baseReaderSettings.ConformanceLevel && this.conformanceLevel != ConformanceLevel.Auto)
                {
                    throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
                }
                if (this.checkCharacters && !baseReaderSettings.CheckCharacters)
                {
                    checkChars = true;
                    needWrap   = true;
                }
                if (this.ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace)
                {
                    noWhitespace = true;
                    needWrap     = true;
                }
                if (this.ignoreComments && !baseReaderSettings.IgnoreComments)
                {
                    noComments = true;
                    needWrap   = true;
                }
                if (this.ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions)
                {
                    noPIs    = true;
                    needWrap = true;
                }

                if ((this.dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) ||
                    (this.dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse))
                {
                    dtdProc  = this.dtdProcessing;
                    needWrap = true;
                }
            }

            if (needWrap)
            {
                IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
                if (readerAsNSResolver != null)
                {
                    return(new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc));
                }
                else
                {
                    return(new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc));
                }
            }
            else
            {
                return(baseReader);
            }
        }
示例#44
0
        internal XmlReader AddConformanceWrapper(XmlReader baseReader)
        {
            XmlReaderSettings baseReaderSettings = baseReader.Settings;
            bool          checkChars             = false;
            bool          noWhitespace           = false;
            bool          noComments             = false;
            bool          noPIs    = false;
            DtdProcessing dtdProc  = (DtdProcessing)(-1);
            bool          needWrap = false;

            if (baseReaderSettings == null)
            {
#pragma warning disable 618

                if (_conformanceLevel != ConformanceLevel.Auto && _conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))
                {
                    throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
                }

                // get the V1 XmlTextReader ref
                XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
                if (v1XmlTextReader == null)
                {
                    XmlValidatingReader vr = baseReader as XmlValidatingReader;
                    if (vr != null)
                    {
                        v1XmlTextReader = (XmlTextReader)vr.Reader;
                    }
                }

                // assume the V1 readers already do all conformance checking;
                // wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
                if (_ignoreWhitespace)
                {
                    WhitespaceHandling wh = WhitespaceHandling.All;
                    // special-case our V1 readers to see if whey already filter whitespaces
                    if (v1XmlTextReader != null)
                    {
                        wh = v1XmlTextReader.WhitespaceHandling;
                    }
                    if (wh == WhitespaceHandling.All)
                    {
                        noWhitespace = true;
                        needWrap     = true;
                    }
                }
                if (_ignoreComments)
                {
                    noComments = true;
                    needWrap   = true;
                }
                if (_ignorePIs)
                {
                    noPIs    = true;
                    needWrap = true;
                }
                // DTD processing
                DtdProcessing baseDtdProcessing = DtdProcessing.Parse;
                if (v1XmlTextReader != null)
                {
                    baseDtdProcessing = v1XmlTextReader.DtdProcessing;
                }

                if ((_dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) ||
                    (_dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse))
                {
                    dtdProc  = _dtdProcessing;
                    needWrap = true;
                }
#pragma warning restore 618
            }
            else
            {
                if (_conformanceLevel != baseReaderSettings.ConformanceLevel && _conformanceLevel != ConformanceLevel.Auto)
                {
                    throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
                }
                if (_checkCharacters && !baseReaderSettings.CheckCharacters)
                {
                    checkChars = true;
                    needWrap   = true;
                }
                if (_ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace)
                {
                    noWhitespace = true;
                    needWrap     = true;
                }
                if (_ignoreComments && !baseReaderSettings.IgnoreComments)
                {
                    noComments = true;
                    needWrap   = true;
                }
                if (_ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions)
                {
                    noPIs    = true;
                    needWrap = true;
                }

                if ((_dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) ||
                    (_dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse))
                {
                    dtdProc  = _dtdProcessing;
                    needWrap = true;
                }
            }

            if (needWrap)
            {
                IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
                if (readerAsNSResolver != null)
                {
                    return(new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc));
                }
                else
                {
                    return(new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc));
                }
            }
            else
            {
                return(baseReader);
            }
        }
示例#45
0
        public void TestLoadSaveXmlValidate()
        {
            // Load the schema

            var xmlSchemaSet = new Xml.Schema.XmlSchemaSet();

            xmlSchemaSet.XmlResolver = new Xml.XmlUrlResolver();

            string schemaPath = Path.Combine(
                TestContext.CurrentContext.TestDirectory,
                "Resources\\schemas\\xml\\AAS.xsd");

            xmlSchemaSet.Add(null, schemaPath);

            var schemaMessages = new List <string>();

            xmlSchemaSet.ValidationEventHandler +=
                (object sender, Xml.Schema.ValidationEventArgs e) => { schemaMessages.Add(e.Message); };
            xmlSchemaSet.Compile();

            if (schemaMessages.Count > 0)
            {
                var parts = new List <string> {
                    $"Failed to compile the schema: {schemaPath}"
                };
                parts.AddRange(schemaMessages);

                throw new InvalidOperationException(string.Join(Environment.NewLine, parts));
            }

            // Load-Save-Validate

            List <string> aasxPaths = SamplesAasxDir.ListAasxPaths();

            using (var tmpDir = new TemporaryDirectory())
            {
                string tmpDirPath = tmpDir.Path;

                foreach (string aasxPath in aasxPaths)
                {
                    using (var package = new AdminShellPackageEnv(aasxPath))
                    {
                        string name    = Path.GetFileName(aasxPath);
                        string outPath = System.IO.Path.Combine(tmpDirPath, $"{name}.converted.xml");

                        package.SaveAs(outPath, writeFreshly: true);

                        var settings = new Xml.XmlReaderSettings();
                        settings.ValidationType = Xml.ValidationType.Schema;
                        settings.Schemas        = xmlSchemaSet;

                        var messages = new List <string>();
                        settings.ValidationEventHandler +=
                            (object sender, Xml.Schema.ValidationEventArgs e) =>
                        {
                            messages.Add(e.Message);
                        };

                        using (var reader = Xml.XmlReader.Create(outPath, settings))
                        {
                            while (reader.Read())
                            {
                                // Invoke callbacks
                            }
                            ;

                            if (messages.Count > 0)
                            {
                                var parts = new List <string>
                                {
                                    $"Failed to validate XML file exported from {aasxPath} to {outPath}:"
                                };
                                parts.AddRange(messages);

                                throw new AssertionException(string.Join(Environment.NewLine, parts));
                            }
                        }
                    }
                }
            }
        }
示例#46
0
        public static XmlReader Create(Stream input)
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            return(XmlReader.CreateReaderImpl(input, settings, "", settings.CloseInput));
        }
示例#47
0
        static void Main(string[] args)
        {
            //Holds all of the argument paths we may get given
            ArgHolder pathArg       = new ArgHolder();
            ArgHolder interfaceArg  = new ArgHolder();
            ArgHolder serviceArg    = new ArgHolder();
            ArgHolder proxyArg      = new ArgHolder();
            ArgHolder contractArg   = new ArgHolder();
            ArgHolder wcfserviceArg = new ArgHolder();
            ArgHolder hostArg       = new ArgHolder();

            bool bVerbose         = false; //Verbosity level
            bool bOutputSpecified = false; //Whether any output values have been set

            #region argParsing
            for (int i = 0; i < args.Length; i++)
            {
                string    arg    = args[i].ToLower();
                ArgHolder holder = null;

                if (arg.StartsWith("--")) // If long param
                {
                    switch (arg)
                    {
                    case "--path":
                        holder = pathArg;
                        break;

                    case "--interface":
                        holder = interfaceArg;
                        break;

                    case "--service":
                        holder = serviceArg;
                        break;

                    case "--proxy":
                        holder = proxyArg;
                        break;

                    case "--contract":
                        holder = contractArg;
                        break;

                    case "--wcfservice":
                        holder = wcfserviceArg;
                        break;

                    case "--host":
                        holder = hostArg;
                        break;

                    case "--verbose":
                        bVerbose = true;
                        break;

                    default:
                        Console.Error.WriteLine(args[i] + " not a valid argument");
                        break;
                    }
                } // Ends if long param
                else if (arg.StartsWith("-")) // Else if short param
                {
                    switch (arg)
                    {
                    case "-p":
                        holder = pathArg;
                        break;

                    case "-i":
                        holder = interfaceArg;
                        break;

                    case "-s":
                        holder = serviceArg;
                        break;

                    case "-x":
                        holder = proxyArg;
                        break;

                    case "-c":
                        holder = contractArg;
                        break;

                    case "-w":
                        holder = wcfserviceArg;
                        break;

                    case "-h":
                        holder = hostArg;
                        break;

                    case "-v":
                        bVerbose = true;
                        break;

                    default:
                        Console.Error.WriteLine(args[i] + " not a valid argument");
                        break;
                    }
                } // Ends else if short param
                else
                {
                    if (arg == "/?")
                    {
                        Usage();
                    }
                    else
                    {
                        Console.Error.WriteLine(args[i] + " not a valid argument");
                    }
                }

                //If given a parameter that comes as two args, i.e. arg & path, consume an extra arg this loop
                if (holder != null)
                {
                    i++;
                    if (i >= args.Length)
                    {
                        Console.Error.WriteLine(string.Format("Insufficient number of arguments provided."));
                        Usage();
                    }
                    holder.Arg = args[i];
                    if (holder != pathArg)
                    {
                        bOutputSpecified = true;
                    }
                }
            } // Ends loop over args
            #endregion argParsing

            // Check we were given an input file at least
            if (pathArg.Arg == null)
            {
                System.Console.Error.WriteLine("No input path specified");
                Usage();
            }

            // If no output parameters specified, just spit out all code to default files
            if (!bOutputSpecified)
            {
                interfaceArg.Arg  = DefaultInterfaceFile;
                serviceArg.Arg    = DefaultImplementationFile;
                proxyArg.Arg      = DefaultProxyFile;
                contractArg.Arg   = DefaultContractFile;
                wcfserviceArg.Arg = DefaultWCFServiceFile;
                hostArg.Arg       = DefaultHostFile;
            } // Ends if no output parameters specified

            #region outputWriters
            // Initialise all writers to null
            TextWriter writerInterface  = null;
            TextWriter writerService    = null;
            TextWriter writerProxy      = null;
            TextWriter writerContract   = null;
            TextWriter writerWCFService = null;
            TextWriter writerHost       = null;

            //Lets us print out info in exceptions if anything goes wrong
            string exceptionInfoString = "";
            string givenArg            = "";
            //try-catch-bail
            try
            {
                //try-catch-info-throw
                try
                {
                    //Only open the files we've been told to care about
                    //i.e. We need to prevent any ArgumentNullExceptions as it's a valid use case
                    exceptionInfoString = "Service Interface";
                    givenArg            = interfaceArg.Arg;
                    if (givenArg != null)
                    {
                        writerInterface = new StreamWriter(givenArg);
                    }

                    exceptionInfoString = "Service Implementation";
                    givenArg            = serviceArg.Arg;
                    if (givenArg != null)
                    {
                        writerService = new StreamWriter(givenArg);
                    }

                    exceptionInfoString = "Client Proxy";
                    givenArg            = proxyArg.Arg;
                    if (givenArg != null)
                    {
                        writerProxy = new StreamWriter(givenArg);
                    }

                    exceptionInfoString = "WCF Contract";
                    givenArg            = contractArg.Arg;
                    if (givenArg != null)
                    {
                        writerContract = new StreamWriter(givenArg);
                    }

                    exceptionInfoString = "WCF Service";
                    givenArg            = wcfserviceArg.Arg;
                    if (givenArg != null)
                    {
                        writerWCFService = new StreamWriter(givenArg);
                    }

                    exceptionInfoString = "WCF Host";
                    givenArg            = hostArg.Arg;
                    if (givenArg != null)
                    {
                        writerHost = new StreamWriter(givenArg);
                    }
                }
                catch (System.ArgumentException sae)
                {
                    System.Console.Error.WriteLine("Bad output path {0} given for {1}", givenArg, exceptionInfoString);
                    throw sae;
                }
                catch (System.UnauthorizedAccessException uae)
                {
                    System.Console.Error.WriteLine("Unauthorised access to {0} given for {1}", givenArg, exceptionInfoString);
                    throw uae;
                }
                catch (System.IO.DirectoryNotFoundException dnfe)
                {
                    System.Console.Error.WriteLine("Invalid directory in path {0} given for {1}", givenArg, exceptionInfoString);
                    throw dnfe;
                }
                catch (System.IO.PathTooLongException ptle)
                {
                    System.Console.Error.WriteLine("The specified path, file name, or both in {0} given for {1}, exceeds the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.", givenArg, exceptionInfoString);
                    throw ptle;
                }
                catch (Exception ex)
                {
                    System.Console.Error.Write(ex.ToString()); //Cover any missed bases
                    throw ex;
                }//End try-catch-info-throw
            }
            catch (Exception)
            {
                Environment.Exit(0);
            }//End try-catch-bail

            //May be that we're being watched by a debugger and need to output in two directions at once
            if (System.Diagnostics.Debugger.IsAttached)
            {
                TextWriter writerDebug = new TextWriterDebug();
                writerInterface  = writerInterface != null ? new TextWriterMulti(writerInterface, writerDebug) : null;
                writerService    = writerService != null ? new TextWriterMulti(writerService, writerDebug) : null;
                writerProxy      = writerProxy != null ? new TextWriterMulti(writerProxy, writerDebug) : null;
                writerContract   = writerContract != null ? new TextWriterMulti(writerContract, writerDebug) : null;
                writerWCFService = writerWCFService != null ? new TextWriterMulti(writerWCFService, writerDebug) : null;
                writerHost       = writerHost != null ? new TextWriterMulti(writerHost, writerDebug) : null;
            }

            TextWriters textwriters = new TextWriters
            {
                writerInterface    = writerInterface,
                writerService      = writerService,
                writerProxy        = writerProxy,
                writerWCFContracts = writerContract,
                writerWCFService   = writerWCFService,
                writerWCFHost      = writerHost
            };
            #endregion outputWriters

            //Output info if in verbose
            if (bVerbose)
            {
                System.Console.WriteLine(string.Format("// IDL input path: \"{0}\"", pathArg.Arg));
                System.Diagnostics.Debug.WriteLine(string.Format("// IDL input path: \"{0}\"", pathArg.Arg));

                foreach (TextWriter textwriter in textwriters.GenTextWriters())
                {
                    if (textwriter != null)
                    {
                        System.Console.WriteLine(string.Format("// Output path: \"{0}\"", ((FileStream)((StreamWriter)textwriter).BaseStream).Name));
                        System.Diagnostics.Debug.WriteLine(string.Format("// Output path: \"{0}\"", ((FileStream)((StreamWriter)textwriter).BaseStream).Name));
                    }
                }
            }


            System.Xml.XmlReaderSettings readerSettings = new System.Xml.XmlReaderSettings();
            readerSettings.DtdProcessing    = System.Xml.DtdProcessing.Ignore;
            readerSettings.ValidationType   = ValidationType.None;
            readerSettings.ConformanceLevel = System.Xml.ConformanceLevel.Auto;
            readerSettings.CloseInput       = true;

            //Try to open the input xml file and generate the output code
            try
            {
                try
                {
                    if (pathArg.Arg != null)
                    {
                        BuildCodeFromDbusIDL(XmlReader.Create(pathArg.Arg, readerSettings), textwriters);
                    }
                }
                catch (System.IO.FileNotFoundException fne)
                {
                    System.Console.Error.WriteLine("Could not find the input file {0}", pathArg.Arg);
                    throw fne;
                }
                catch (System.UriFormatException ufe)
                {
                    System.Console.Error.WriteLine("URI Formatting exception for input file {0}", pathArg.Arg);
                    throw ufe;
                }
            }
            catch (Exception)
            {
                Environment.Exit(0);
            }

            //Close everything
            textwriters.Close();

            //If debugger attached, wait for them to tell us to quit
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("Press a key to continue...");
                Console.ReadKey(true);
            }
        }
示例#48
0
 public static XmlReader Create(Stream input, XmlReaderSettings settings)
 {
     return(XmlReader.Create(input, settings, ""));
 }
示例#49
0
        protected override void DownloadComplete(WebDownload downloadInfo)
        {
            try
            {
                downloadInfo.Verify();

                // --- Load Response into XML Document and convert to real image ---

                System.Xml.XmlDocument       hResponseDocument = new System.Xml.XmlDocument();
                System.Xml.XmlReaderSettings oSettings         = new System.Xml.XmlReaderSettings();
                oSettings.IgnoreWhitespace = true;
                System.Xml.XmlReader oResponseXmlStream = System.Xml.XmlReader.Create(downloadInfo.ContentStream, oSettings);
                hResponseDocument.Load(oResponseXmlStream);
                SaveDAPImage(hResponseDocument, downloadInfo.SavedFilePath);

                // --- search for an error ---

                System.Xml.XmlNodeList hNodeList = hResponseDocument.SelectNodes("//" + Geosoft.Dap.Xml.Common.Constant.Tag.ERROR_TAG);
                if (hNodeList.Count >= 1)
                {
                    System.Xml.XmlNode hNode = hNodeList[0];

                    throw new Geosoft.Dap.DapException(hNode.InnerText);
                }

                m_tile.TileSet.NumberRetries = 0;

                // Rename temp file to real name
                File.Delete(m_localFilePath);
                File.Move(downloadInfo.SavedFilePath, m_localFilePath);

                // Make the tile reload the new image
                m_tile.DownloadRequests.Remove(this);
                m_tile.Initialize();
            }
            catch (System.Net.WebException caught)
            {
                System.Net.HttpWebResponse response = caught.Response as System.Net.HttpWebResponse;
                if (response != null && response.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    using (File.Create(m_localFilePath + ".txt"))
                    { }
                    return;
                }
                Log.Write(Log.Levels.Error, "DGDR", "web exception occurred");
                Log.Write(Log.Levels.Error, "DGDR", "Dataset Name: " + (m_DapImageStore.DataSet == null ? "Browser Map" : m_DapImageStore.DataSet.Name));
                Log.Write(Log.Levels.Error, "DGDR", "West: " + Tile.West + " South: " + Tile.South + " East: " + Tile.East + " North: " + Tile.North);
                m_tile.TileSet.NumberRetries++;
            }
            catch
            {
                using (File.Create(m_localFilePath + ".txt"))
                { }
                if (File.Exists(downloadInfo.SavedFilePath))
                {
                    try
                    {
                        File.Delete(downloadInfo.SavedFilePath);
                    }
                    catch (Exception e)
                    {
                        Log.Write(Log.Levels.Error, "GSDR", "could not delete file " + downloadInfo.SavedFilePath + ":");
                        Log.Write(e);
                    }
                }
            }
            finally
            {
                if (download != null)
                {
                    download.IsComplete = true;
                }

                // Immediately queue next download
                m_tile.TileSet.RemoveFromDownloadQueue(this, true);
            }
        }
        public static int ValidateXML(AasValidationRecordList recs, Stream xmlContent)
        {
            // see: AasxCsharpLibrary.Tests/TestLoadSave.cs
            var newRecs = new AasValidationRecordList();

            // access
            if (recs == null || xmlContent == null)
            {
                return(-1);
            }

            // Load the schema files
            var files = GetSchemaResources(SerializationFormat.XML);

            if (files == null)
            {
                return(-1);
            }

            var xmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();

            xmlSchemaSet.XmlResolver = new System.Xml.XmlUrlResolver();

            try
            {
                Assembly myAssembly = Assembly.GetExecutingAssembly();
                foreach (var schemaFn in files)
                {
                    using (Stream schemaStream = myAssembly.GetManifestResourceStream(schemaFn))
                    {
                        using (XmlReader schemaReader = XmlReader.Create(schemaStream))
                        {
                            xmlSchemaSet.Add(null, schemaReader);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new FileNotFoundException("ValidateXML: Error accessing embedded resource schema files: " +
                                                ex.Message);
            }

            // set up messages
            xmlSchemaSet.ValidationEventHandler += (object sender, System.Xml.Schema.ValidationEventArgs e) =>
            {
                newRecs.Add(new AasValidationRecord(AasValidationSeverity.Serialization, null,
                                                    "" + e?.Exception?.LineNumber + ", " + e?.Exception?.LinePosition + ": " + e?.Message));
            };

            // compile
            try
            {
                xmlSchemaSet.Compile();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("ValidateXML: Error compiling schema files: " +
                                                    ex.Message);
            }

            if (newRecs.Count > 0)
            {
                var parts = new List <string> {
                    $"Failed to compile the schema files:"
                };
                parts.AddRange(newRecs.Select <AasValidationRecord, string>((r) => r.Message));
                throw new InvalidOperationException(string.Join(Environment.NewLine, parts));
            }

            // load/ validate on same records
            var settings = new System.Xml.XmlReaderSettings();

            settings.ValidationType = System.Xml.ValidationType.Schema;
            settings.Schemas        = xmlSchemaSet;

            settings.ValidationEventHandler +=
                (object sender, System.Xml.Schema.ValidationEventArgs e) =>
            {
                newRecs.Add(new AasValidationRecord(AasValidationSeverity.Serialization, null,
                                                    "XML: " + e?.Exception?.LineNumber + ", " + e?.Exception?.LinePosition + ": " + e?.Message));
            };

            // use the xml stream
            using (var reader = System.Xml.XmlReader.Create(xmlContent, settings))
            {
                while (reader.Read())
                {
                    // Invoke callbacks
                }
                ;
            }

            // result
            recs.AddRange(newRecs);
            return(newRecs.Count);
        }
示例#51
0
        internal XmlReader AddConformanceWrapper(XmlReader baseReader)
        {
            XmlReaderSettings settings = baseReader.Settings;
            bool checkCharacters       = false;
            bool ignoreWhitespace      = false;
            bool ignoreComments        = false;
            bool ignorePis             = false;

            System.Xml.DtdProcessing dtdProcessing = ~System.Xml.DtdProcessing.Prohibit;
            bool flag5 = false;

            if (settings == null)
            {
                if ((this.conformanceLevel != System.Xml.ConformanceLevel.Auto) && (this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)))
                {
                    throw new InvalidOperationException(Res.GetString("Xml_IncompatibleConformanceLevel", new object[] { this.conformanceLevel.ToString() }));
                }
                XmlTextReader reader = baseReader as XmlTextReader;
                if (reader == null)
                {
                    XmlValidatingReader reader2 = baseReader as XmlValidatingReader;
                    if (reader2 != null)
                    {
                        reader = (XmlTextReader)reader2.Reader;
                    }
                }
                if (this.ignoreWhitespace)
                {
                    WhitespaceHandling all = WhitespaceHandling.All;
                    if (reader != null)
                    {
                        all = reader.WhitespaceHandling;
                    }
                    if (all == WhitespaceHandling.All)
                    {
                        ignoreWhitespace = true;
                        flag5            = true;
                    }
                }
                if (this.ignoreComments)
                {
                    ignoreComments = true;
                    flag5          = true;
                }
                if (this.ignorePIs)
                {
                    ignorePis = true;
                    flag5     = true;
                }
                System.Xml.DtdProcessing parse = System.Xml.DtdProcessing.Parse;
                if (reader != null)
                {
                    parse = reader.DtdProcessing;
                }
                if (((this.dtdProcessing == System.Xml.DtdProcessing.Prohibit) && (parse != System.Xml.DtdProcessing.Prohibit)) || ((this.dtdProcessing == System.Xml.DtdProcessing.Ignore) && (parse == System.Xml.DtdProcessing.Parse)))
                {
                    dtdProcessing = this.dtdProcessing;
                    flag5         = true;
                }
            }
            else
            {
                if ((this.conformanceLevel != settings.ConformanceLevel) && (this.conformanceLevel != System.Xml.ConformanceLevel.Auto))
                {
                    throw new InvalidOperationException(Res.GetString("Xml_IncompatibleConformanceLevel", new object[] { this.conformanceLevel.ToString() }));
                }
                if (this.checkCharacters && !settings.CheckCharacters)
                {
                    checkCharacters = true;
                    flag5           = true;
                }
                if (this.ignoreWhitespace && !settings.IgnoreWhitespace)
                {
                    ignoreWhitespace = true;
                    flag5            = true;
                }
                if (this.ignoreComments && !settings.IgnoreComments)
                {
                    ignoreComments = true;
                    flag5          = true;
                }
                if (this.ignorePIs && !settings.IgnoreProcessingInstructions)
                {
                    ignorePis = true;
                    flag5     = true;
                }
                if (((this.dtdProcessing == System.Xml.DtdProcessing.Prohibit) && (settings.DtdProcessing != System.Xml.DtdProcessing.Prohibit)) || ((this.dtdProcessing == System.Xml.DtdProcessing.Ignore) && (settings.DtdProcessing == System.Xml.DtdProcessing.Parse)))
                {
                    dtdProcessing = this.dtdProcessing;
                    flag5         = true;
                }
            }
            if (!flag5)
            {
                return(baseReader);
            }
            IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;

            if (readerAsNSResolver != null)
            {
                return(new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkCharacters, ignoreWhitespace, ignoreComments, ignorePis, dtdProcessing));
            }
            return(new XmlCharCheckingReader(baseReader, checkCharacters, ignoreWhitespace, ignoreComments, ignorePis, dtdProcessing));
        }
示例#52
0
        public static int Leer()
        {
            //pone los valores por defecto a las variables
            latitud      = 0;
            longitud     = 0;
            segundos     = 5;
            minutos      = 50;
            gps          = "GPS";
            avisoauto    = false;
            avisomapa    = false;
            avisomapaurl = true;
            avisoheight  = 475;
            avisowidth   = 450;
            avisotop     = 0;
            avisoleft    = 0;
            port         = "NONE";
            speed        = "NONE";
            usuario      = "nombre_usuario";
            clave        = " ";
            //averigua el idioma del usuario
            //System.Threading.Thread tt = System.Threading.Thread.CurrentThread;   //PDA
            //System.Globalization.CultureInfo actual = tt.CurrentCulture;          //PDA

            string actual = System.Globalization.CultureInfo.CurrentCulture.Name;

            if (actual.Substring(0, 2) == "es")
            {
                idioma = "ES";
            }
            else
            {
                idioma = "EN";
            }
            sonido     = "ringin.wav";
            explorador = "hipoqih";
            //primero hay que leer configuracion del XML
            System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
            try
            {
                string tmp       = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;                // PDA
                string strAppDir = tmp.Substring(1, tmp.Length - 11);                                                   //le quito \\plugin.exe       // PDA
                using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(strAppDir + "\\config.xml", settings)) //PDA
                {
                    // Read XML data.
                    reader.ReadStartElement("config");
                    System.Globalization.NumberFormatInfo nfi = new System.Globalization.CultureInfo("en-US", false).NumberFormat;
                    latitud      = double.Parse(reader.ReadElementString("lat"), nfi);
                    longitud     = double.Parse(reader.ReadElementString("lon"), nfi);
                    segundos     = int.Parse(reader.ReadElementString("tick"));
                    minutos      = int.Parse(reader.ReadElementString("tack"));
                    gps          = reader.ReadElementString("gps");
                    avisoauto    = bool.Parse(reader.ReadElementString("auto"));
                    avisomapa    = bool.Parse(reader.ReadElementString("map"));
                    avisomapaurl = bool.Parse(reader.ReadElementString("mapurl"));
                    avisowidth   = int.Parse(reader.ReadElementString("width"));
                    avisoheight  = int.Parse(reader.ReadElementString("height"));
                    avisotop     = int.Parse(reader.ReadElementString("top"));
                    avisoleft    = int.Parse(reader.ReadElementString("left"));
                    port         = reader.ReadElementString("port");
                    speed        = reader.ReadElementString("speed");
                    usuario      = reader.ReadElementString("user");
                    clave        = reader.ReadElementString("pass");
                    idioma       = reader.ReadElementString("lang");
                    sonido       = reader.ReadElementString("song");
                    explorador   = reader.ReadElementString("explorer");
                }
                //ok
                return(0);
            }
            catch
            {
                //si da algun error intenta crear los datos que faltan
                Grabar();
                //se creo de nuevo...
                return(1);
            }
        }