Close() public method

public Close ( ) : void
return void
Esempio n. 1
0
        public BaseCodeGenerator(Stream sourceXML) 
        {
            XmlDocument doc = new XmlDocument();
            using (sourceXML)
            {
                doc.Load(sourceXML);
            }

            MemoryStream ms = new MemoryStream();
            doc.Save(ms);

            ms.Position = 0;

            using (XmlTextReader r = new XmlTextReader(ms))
            {
                XmlValidatingReader v = new XmlValidatingReader(r);
                v.ValidationType = ValidationType.Schema;
                v.ValidationEventHandler += new ValidationEventHandler(v_ValidationEventHandler);
                while (v.Read())
                {
                }
                v.Close();
            }

            if (m_errors)
                throw new InvalidDataException("The Xml input did not match the schema");

            Parse(doc);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string xmlFile = Server.MapPath("~/Customers1.xml");
            string xsdFile = Server.MapPath("~/Customers.xsd");

            XmlTextReader textReader = new XmlTextReader(xmlFile);
            XmlValidatingReader validatingReader = new XmlValidatingReader(textReader);
            validatingReader.Schemas.Add(null, xsdFile);
            validatingReader.ValidationType = ValidationType.Schema;
            validatingReader.ValidationEventHandler += new ValidationEventHandler(validatingReader_ValidationEventHandler);

            while (validatingReader.Read())
            {
                if (validatingReader.NodeType == XmlNodeType.Element)
                {
                    if (validatingReader.SchemaType is XmlSchemaComplexType)
                    {
                        XmlSchemaComplexType complexType = (XmlSchemaComplexType)validatingReader.SchemaType;
                        Response.Write(validatingReader.Name + " " + complexType.Name);
                    }
                    else
                    {
                        object innerText = validatingReader.ReadTypedValue();
                        Response.Write(validatingReader.Name + " : " + innerText.ToString() + " <br />");
                    }
                }
            }
            validatingReader.Close();
        }
Esempio n. 3
0
        /*Validar archivo XML Contra Esquema XSD*/
        public void Validar(string rutaFicheroXml)
        {
            var r = new XmlTextReader(rutaFicheroXml);
            var v = new XmlValidatingReader(r) {ValidationType = ValidationType.Schema};
            v.ValidationEventHandler += ValidarControlEventos;
            var procesarXml = new ConvertirXmlEnTexo();
            procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/);
            try
            {
                while (v.Read())
                {
                }

                // Comprobar si el documento es válido o no.
                //return _isValid ? "true" : "false";
               // var procesarXml = new ConvertirXmlEnTexo();
               // procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/);
                v.Close();

            }
            catch (Exception e)
            {
                //ValidarControlEventos(null, null);
                // _isValid = false;
                // MessageBox.Show("Evento de validación\r\n" + e.Message, @"Validacion de XML",
                // MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                ////v.ValidationEventHandler += new ValidationEventHandler(ValidarControlEventos);
                //return "true";
            }
        }
Esempio n. 4
0
        /// <summary>
        ///     Valida se um Xml está seguindo de acordo um Schema
        /// </summary>
        /// <param name="arquivoXml">Arquivo Xml</param>
        /// <param name="arquivoSchema">Arquivo de Schema</param>
        /// <returns>True se estiver certo, Erro se estiver errado</returns>
        public void ValidaSchema(String arquivoXml, String arquivoSchema)
        {
            //Seleciona o arquivo de schema de acordo com o schema informado
            //arquivoSchema = Bll.Util.ContentFolderSchemaValidacao + "\\" + arquivoSchema;

            //Verifica se o arquivo de XML foi encontrado.
            if (!File.Exists(arquivoXml))
                throw new Exception("Arquivo de XML informado: \"" + arquivoXml + "\" não encontrado.");

            //Verifica se o arquivo de schema foi encontrado.
            if (!File.Exists(arquivoSchema))
                throw new Exception("Arquivo de schema: \"" + arquivoSchema + "\" não encontrado.");

            // Cria um novo XMLValidatingReader
            var reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(arquivoXml)));
            // Cria um schemacollection
            var schemaCollection = new XmlSchemaCollection();
            //Adiciona o XSD e o namespace
            schemaCollection.Add("http://www.portalfiscal.inf.br/nfe", arquivoSchema);
            // Adiciona o schema ao ValidatingReader
            reader.Schemas.Add(schemaCollection);
            //Evento que retorna a mensagem de validacao
            reader.ValidationEventHandler += Reader_ValidationEventHandler;
            //Percorre o XML
            while (reader.Read())
            {
            }
            reader.Close(); //Fecha o arquivo.
            //O Resultado é preenchido no reader_ValidationEventHandler

            if (validarResultado != "")
            {
                throw new Exception(validarResultado);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Validate XML Format
        /// </summary>
        /// <param name="text">XML string</param>
        public static bool IsValidXML(string text)
        {
            bool errored;

            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(text);
            MemoryStream stream = new MemoryStream(byteArray);

            XmlTextReader xmlr = new XmlTextReader(stream);
            XmlValidatingReader reader = new XmlValidatingReader(xmlr);

            try
            {
                while (reader.Read()) { ; }
                errored = false;
            }
            catch
            {
                errored = true;
            }
            finally
            {
                reader.Close();
            }

            return !errored;
        }
 public static WebReferenceOptions Read(XmlReader xmlReader, ValidationEventHandler validationEventHandler)
 {
     WebReferenceOptions options;
     XmlValidatingReader reader = new XmlValidatingReader(xmlReader) {
         ValidationType = ValidationType.Schema
     };
     if (validationEventHandler != null)
     {
         reader.ValidationEventHandler += validationEventHandler;
     }
     else
     {
         reader.ValidationEventHandler += new ValidationEventHandler(WebReferenceOptions.SchemaValidationHandler);
     }
     reader.Schemas.Add(Schema);
     webReferenceOptionsSerializer serializer = new webReferenceOptionsSerializer();
     try
     {
         options = (WebReferenceOptions) serializer.Deserialize(reader);
     }
     catch (Exception exception)
     {
         throw exception;
     }
     finally
     {
         reader.Close();
     }
     return options;
 }
Esempio n. 7
0
        public GReader(string path)
        {
            document = new XmlDocument ();

            try {
            XmlTextReader textreader = new XmlTextReader (path);
            XmlValidatingReader vreader = new XmlValidatingReader (textreader);

            // Set the validation event handler
              			vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

            // Load the XML to Document node.
            document.Load (textreader);
            Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful!" : "failed."));

            //Close the reader.
            vreader.Close();

            } catch (FileNotFoundException e) {
            Console.WriteLine ("Error: {0} not found.", e.FileName);
            Environment.Exit (1);
            } catch (DirectoryNotFoundException) {
            Console.WriteLine ("Error: {0} not found.", path);
            Environment.Exit (1);
            } catch (XmlException) {
            Console.WriteLine ("Error: {0} is not well-formed xml.", path);
            Environment.Exit (1);
            }
        }
Esempio n. 8
0
        public static T_SeamateItems ParseItemsConfiguration(String configPath)
        {
            TextReader tr = null;

            XmlTextReader xml = null;
            XmlValidatingReader validate = null;
            xml = new XmlTextReader(configPath);
            validate = new XmlValidatingReader(xml);
            validate.ValidationEventHandler += new ValidationEventHandler(xsdValidationHandler);
            while (validate.Read()) { }
            validate.Close();

            try
            {
                tr = new StreamReader(configPath);
                XmlSerializer serializer = new XmlSerializer(typeof(T_SeamateItems));
                T_SeamateItems config = (T_SeamateItems)serializer.Deserialize(tr);
                tr.Close();
                return config;
            }
            catch (Exception ex)
            {
                if (tr != null)
                {
                    tr.Close();
                }

                throw new Exception("Unable to read configuration file: " + configPath, ex);
            }

            return null;
        }
Esempio n. 9
0
        private void ParseDocumentType(XmlDocumentType dtNode, bool bUseResolver, XmlResolver resolver)
        {
            this.doc = dtNode.OwnerDocument;
            XmlNameTable        nt  = this.doc.NameTable;
            XmlNamespaceManager mgr = new XmlNamespaceManager(nt);
            XmlParserContext    pc  = new XmlParserContext(nt,
                                                           mgr,
                                                           dtNode.Name,
                                                           dtNode.PublicId,
                                                           dtNode.SystemId,
                                                           dtNode.InternalSubset,
                                                           this.doc.BaseURI,
                                                           String.Empty,
                                                           XmlSpace.None
                                                           );
            XmlValidatingReader vr = new XmlValidatingReader("", XmlNodeType.Element, pc);

            vr.Namespaces = dtNode.ParseWithNamespaces;
            if (bUseResolver)
            {
                vr.XmlResolver = resolver;
            }
            vr.ValidationType = ValidationType.None;
            vr.Read();
            LoadDocumentType(vr, dtNode);
            vr.Close();
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Invalid parameter count. Exiting...");
                return;
            }

            string xmlFile = args[0];
            string xdsFile = args[1];
            string xdsNamespace = args[2];
            string outputFile = args[3];

            try
            {
                XmlSchemaCollection cache = new XmlSchemaCollection();
                cache.Add(xdsNamespace, xdsFile);

                XmlTextReader r = new XmlTextReader(xmlFile);
                XmlValidatingReader v = new XmlValidatingReader(r);
                v.Schemas.Add(cache);

                v.ValidationType = ValidationType.Schema;

                v.ValidationEventHandler +=
                    new ValidationEventHandler(MyValidationEventHandler);

                while (v.Read()) { } // look for validation errors
                v.Close();
            }
            catch (Exception e)
            {
                encounteredFatalError = true;
                fatalError = e;
            }

            StreamWriter file = new StreamWriter(outputFile);

            if (isValid && !encounteredFatalError)
                file.WriteLine("PASSED: Document is valid");
            else
                file.WriteLine("FAILED: Document is invalid");

            // Printing
            foreach (string entry in list)
            {
                file.WriteLine(entry);
            }
            if (encounteredFatalError)
            {
                file.WriteLine("Error: a FATAL error has occured " +
                        "while reading the file.\r\n" + fatalError.ToString());
            }
            file.Close();
        }
Esempio n. 11
0
        static void Main(string[] args)
        {

            XmlTextReader r = new XmlTextReader(@"..\..\XMLFile1.xml");
            XmlValidatingReader v = new XmlValidatingReader(r);
            v.ValidationType = ValidationType.Schema;
            v.ValidationEventHandler += 
               new ValidationEventHandler(MyValidationEventHandler);

            while(v.Read())
            {
                // Can add code here to process the content.
            }
            v.Close();

            // Check whether the document is valid or invalid.
            if(m_isValid)
            {
                Console.WriteLine("Document is valid");
            }
            else
            {
                Console.WriteLine("Document is invalid");
            }


            
        /*
            XmlTextWriter xtw = new XmlTextWriter(new StreamWriter("test1.xml"));
            
            xtw.WriteStartDocument(true);
            xtw.WriteStartElement("MapVals");
            
            xtw.WriteStartElement("MapValKey1");
            xtw.WriteAttributeString("val1","a");
            xtw.WriteAttributeString("val2","b");
            xtw.WriteEndElement();
            
            xtw.WriteStartElement("MapValKey2");
            xtw.WriteAttributeString("val1","qf");
            xtw.WriteAttributeString("val2","xt");
            xtw.WriteEndElement();
            
            xtw.WriteStartElement("MapValKey3");
            xtw.WriteAttributeString("val1","wwu");
            xtw.WriteAttributeString("val2","verble");
            xtw.WriteEndElement();
            
            xtw.WriteEndElement();
            
            xtw.WriteEndDocument();
            xtw.Close();
        */
        }
Esempio n. 12
0
        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="directory"></param>
        /// <param name="ruleName"></param>
        /// 
        /// <returns></returns>
        /// 
        public static List<RuleItem> Read(string directory, string ruleName)
        {
            List<RuleItem> result = new List<RuleItem>();

            foreach (string file in Directory.GetFiles(directory, "*.xml"))
            {
                XmlValidatingReader reader = null;
                try
                {
                    XmlDocument xml = new XmlDocument();
                    reader = new XmlValidatingReader(new XmlTextReader(file));
                    reader.ValidationType = ValidationType.None;
                    xml.Load(reader);
                    reader.Close();

                    XmlElement rootNode = (XmlElement) xml.SelectSingleNode("/applicationlogic");
                    XmlNodeList ruleNodes = rootNode.SelectNodes(ruleName);

                    // extract each rule.
                    foreach (XmlElement ruleSource in ruleNodes)
                    {
                        RuleItem rule = new RuleItem(ruleName, xml, ruleSource, directory, file);
                        result.Add(rule);
                    }

                }
                catch (Exception exception)
                {
                    log.Warn(string.Format("Failed to read rules file: {0}.", file), exception);
                }
                finally
                {
                    if (reader != null && reader.ReadState != ReadState.Closed)
                    {
                        reader.Close();
                    }
                }
            }

            return result;
        }
Esempio n. 13
0
		public XPathDocument (string uri, XmlSpace space)
		{
			XmlValidatingReader vr = null;
			try {
				vr = new XmlValidatingReader (new XmlTextReader (uri));
				vr.ValidationType = ValidationType.None;
				Initialize (vr, space);
			} finally {
				if (vr != null)
					vr.Close ();
			}
		}
Esempio n. 14
0
        public void Validate(string strXMLDoc)
        {
            try
            {
                // Declare local objects
                XmlTextReader tr = null;
                XmlSchemaCollection xsc = null;
                XmlValidatingReader vr = null;

                // Text reader object
                tr = new XmlTextReader(Application.StartupPath + @"\BDOCImportSchema.xsd");
                xsc = new XmlSchemaCollection();
                xsc.Add(null, tr);

                // XML validator object

                vr = new XmlValidatingReader(strXMLDoc,
                             XmlNodeType.Document, null);

                vr.Schemas.Add(xsc);

                // Add validation event handler

                vr.ValidationType = ValidationType.Schema;
                vr.ValidationEventHandler +=
                         new ValidationEventHandler(ValidationHandler);

                // Validate XML data

                while (vr.Read()) ;

                vr.Close();

                // Raise exception, if XML validation fails
                if (ErrorsCount > 0)
                {
                    throw new Exception(ErrorMessage);
                }

                // XML Validation succeeded
                Console.WriteLine("XML validation succeeded.\r\n");
            }
            catch (Exception error)
            {
                // XML Validation failed
                Console.WriteLine("XML validation failed." + "\r\n" +
                "Error Message: " + error.Message);
                throw new Exception("Error in XSD verification:\r\n" + error.Message);
            }
        }
Esempio n. 15
0
		private void Render(Stream stream, string xslResourceId, string xslResourceDefault, XsltArgumentList args) {
			XslTransform xslt = new XslTransform();
			xslt.Load(new XmlTextReader(Assembly
			                            .GetExecutingAssembly()
			                            .GetManifestResourceStream(Parameter.GetString(xslResourceId, xslResourceDefault))),
                null,
                null);
			
			XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(ruleFileURI));
			reader.ValidationType = ValidationType.Schema;
			reader.Schemas.Add(XmlSchema.Read(Assembly
						                            .GetExecutingAssembly()
                                                    .GetManifestResourceStream(Parameter.GetString("xbusinessrules.xsd", "resource.xBusinessRules.xsd")),
						               							null));
			xslt.Transform(new XPathDocument(reader), args, stream, null);
			reader.Close();
		}
Esempio n. 16
0
		static void ValidateFile (string file)
		{
			IsValid = true;
			try {
				reader = new XmlValidatingReader (new XmlTextReader (file));
				reader.ValidationType = ValidationType.Schema;
				reader.Schemas.Add (schema);
				reader.ValidationEventHandler += new ValidationEventHandler (OnValidationEvent);
				while (reader.Read ()) {
					// do nothing
				}
				reader.Close ();
			}
			catch (Exception e) {
				Console.WriteLine ("mdvalidator: error: " + e.ToString ());
			}
		}
Esempio n. 17
0
        public bool ValidateXMLFile()
        {
            XmlTextReader objXmlTextReader =null;
            XmlValidatingReader objXmlValidatingReader=null ;

            try
            {
                //creating a text reader for the XML file already picked by the
                //overloaded constructor above viz..clsSchemaValidator
                objXmlTextReader = new XmlTextReader(m_sXMLFileName);
                //creating a validating reader for that objXmlTextReader just created
                objXmlValidatingReader = new XmlValidatingReader (objXmlTextReader);
                //For validation we are adding the schema collection in
                //ValidatingReaders Schema collection.
                objXmlValidatingReader.Schemas.Add (m_objXmlSchemaCollection);
                //Attaching the event handler now in case of failures
                objXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler
                    (ValidationFailed);
                //Actually validating the data in the XML file with a empty while.
                //which would fire the event ValidationEventHandler and invoke
                //our ValidationFailed function
                while (objXmlValidatingReader.Read())
                {
                }
                //Note:- If any issue is faced in the above while it will invoke ValidationFailed
                //which will in turn set the module level m_bIsFailure boolean variable to false
                //thus returning true as a signal to the calling function that the ValidateXMLFile
                //function(this function) has encountered failure
                return m_bIsFailure;
            }
            catch (Exception ex)
            {
                MessageBox.Show ("Exception : " + ex.Message);
                return true;
            }
            finally
            {
                // close the readers, no matter what.
                objXmlValidatingReader.Close ();
                objXmlTextReader.Close ();
            }
        }
    /* Takes a type name, and a valid example of that type, 
       Creates a schema consisting of a single element of that
       type, and validates a bit of xml containing the valid 
       value, with whitespace against that schema.
     
FIXME: Really we want to test the value of whitespace more
       directly that by creating a schema then parsing a string.
     
     */

    public void WhiteSpaceTest(string type, string valid) {
      passed = true;
      XmlSchema schema = new XmlSchema();

      schema.TargetNamespace= "http://example.com/testCase";
      XmlSchemaElement element = new XmlSchemaElement();
      element.Name = "a";
      element.SchemaTypeName = new XmlQualifiedName(type, "http://www.w3.org/2001/XMLSchema");
      schema.Items.Add(element);
      schema.Compile(new ValidationEventHandler(ValidationCallbackOne));

      XmlValidatingReader vr = new XmlValidatingReader(new XmlTextReader(new StringReader("<a xmlns='http://example.com/testCase'>\n\n"+valid+"\n\n</a>" )));
      vr.Schemas.Add(schema);
      vr.ValidationType = ValidationType.Schema;
//      vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
      while(vr.Read()) { };
      vr.Close();
      
      Assert(type + " doesn't collapse whitespace: " + (errorInfo != null ? errorInfo.Message : null), passed);
    }
Esempio n. 19
0
        public bool validateXml(String infile)
        {
            //First we create the xmltextreader
            XmlTextReader xmlr = new XmlTextReader(infile);
            //We pass the xmltextreader into the xmlvalidatingreader
            //'This will validate the xml doc with the schema file
            //'NOTE the xml file it self points to the schema file
            XmlValidatingReader xmlvread = new XmlValidatingReader(xmlr);
            //
            //      //                      ' Set the validation event handler
            xmlvread.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
            m_Success = true; //'make sure to reset the success var
            //
            //      //' Read XML data
            while (xmlvread.Read()) { }

            //'Close the reader.
            xmlvread.Close();

            //'The validationeventhandler is the only thing that would set m_Success to false
            return m_Success;
        }
Esempio n. 20
0
        private static bool isValid = true; // If a validation error occurs,
                                            // set this flag to false in the
                                            // validation event handler. 
        static void Main(string[] args)
        {
            XmlTextReader r = new XmlTextReader(@"..\..\GenKeyIDList.xml");
            XmlValidatingReader v = new XmlValidatingReader(r);
            
            v.ValidationType = ValidationType.Schema;
            v.ValidationEventHandler += 
               new ValidationEventHandler(MyValidationEventHandler);

            while (v.Read())
            {
                // Can add code here to process the content.
                Console.WriteLine(v.LocalName);

                if (v.LocalName == "GenericKeyIDList")
                {
                    if(v.IsStartElement())
                    {
                        v.MoveToFirstAttribute();               
                        v.ReadAttributeValue();
                        Console.WriteLine("    " + v.ReadContentAsString());
                    }
                }
            }
            v.Close();

            // Check whether the document is valid or invalid.
            if (isValid)
            {
               Console.WriteLine("Document is valid");
            }
            else
            {
               Console.WriteLine("Document is invalid");
            }

        
        }
		SchemeNode CreateSchemeNode(XmlTextReader reader, bool userList)
		{
			try 
			{
				XmlValidatingReader validatingReader = new XmlValidatingReader(reader);
				Stream schemaStream = typeof(SyntaxMode).Assembly.GetManifestResourceStream("Mode.xsd");
				validatingReader.Schemas.Add("", new XmlTextReader(schemaStream));
				validatingReader.ValidationType = ValidationType.Schema;
				validatingReader.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
				
				XmlDocument doc = new XmlDocument();
				doc.Load(validatingReader);
				
				if (errors.Count != 0) 
				{
					ReportErrors();
					validatingReader.Close();
					return null;
				} 
				else 
				{
					validatingReader.Close();
					return new SchemeNode(doc.DocumentElement, userList);	
				}
			} 
			catch (Exception e) 
			{
				MessageService.ShowError(e, "${res:Dialog.Options.TextEditorOptions.EditHighlighting.LoadError}");
				return null;
			} 
			finally 
			{
				reader.Close();
			}
			
		}
		/// <summary>
		/// Load and validate the mappings in the <see cref="XmlTextReader" /> against
		/// the nhibernate-mapping-2.0 schema, without adding them to the configuration.
		/// </summary>
		/// <remarks>
		/// This method is made public to be usable from the unit tests. It is not intended
		/// to be called by end users.
		/// </remarks>
		/// <param name="hbmReader">The XmlReader that contains the mapping.</param>
		/// <returns>Validated XmlDocument built from the XmlReader.</returns>
		public XmlDocument LoadMappingDocument( XmlTextReader hbmReader )
		{
			XmlValidatingReader validatingReader = new XmlValidatingReader( hbmReader );

			try
			{
				XmlDocument hbmDocument = new XmlDocument();

				validatingReader.ValidationEventHandler += new ValidationEventHandler( ValidationHandler );
				validatingReader.ValidationType = ValidationType.Schema;
				validatingReader.Schemas.Add( MappingSchemaCollection );

				hbmDocument.Load( validatingReader );
				return hbmDocument;
			}
			finally
			{
				validatingReader.Close();
			}
		}
		/// <summary>
		/// Configure NHibernate using the specified XmlTextReader.
		/// </summary>
		/// <param name="reader">The <see cref="XmlTextReader"/> that contains the Xml to configure NHibernate.</param>
		/// <returns>A Configuration object initialized with the file.</returns>
		/// <remarks>
		/// Calling Configure(XmlTextReader) will overwrite the values set in app.config or web.config
		/// </remarks>
		public Configuration Configure( XmlTextReader reader )
		{
			if( reader == null )
			{
				throw new HibernateException( "Could not configure NHibernate.", new ArgumentException( "A null value was passed in.", "reader" ) );
			}

			XmlDocument doc = new XmlDocument();
			XmlValidatingReader validatingReader = null;

			try
			{
				validatingReader = new XmlValidatingReader( reader );
				validatingReader.ValidationType = ValidationType.Schema;
				validatingReader.Schemas.Add( CfgSchemaCollection );

				doc.Load( validatingReader );
			}
			catch( Exception e )
			{
				log.Error( "Problem parsing configuration", e );
				throw new HibernateException( "problem parsing configuration : " + e );
			}
			finally
			{
				if( validatingReader != null )
				{
					validatingReader.Close();
				}
			}

			return DoConfigure( doc );
		}
Esempio n. 24
0
        /// <summary>
        /// Initializes the task and verifies parameters.
        /// </summary>
        /// <param name="TaskNode">Node that contains the XML fragment used to define this task instance.</param>
        protected override void InitializeTask(XmlNode TaskNode)
        {
            XmlElement taskXml = (XmlElement) TaskNode.Clone();

            // Expand all properties in the task and its child elements
            if (taskXml.ChildNodes != null) {
                ExpandPropertiesInNodes(taskXml.ChildNodes);
                if (taskXml.Attributes != null) {
                    foreach (XmlAttribute attr in taskXml.Attributes) {
                        attr.Value = Properties.ExpandProperties(attr.Value, Location);
                    }
                }
            }

            // Get the [SchemaValidator(type)] attribute
            SchemaValidatorAttribute[] taskValidators =
                (SchemaValidatorAttribute[])GetType().GetCustomAttributes(
                typeof(SchemaValidatorAttribute), true);

            if (taskValidators.Length > 0) {
                SchemaValidatorAttribute taskValidator = taskValidators[0];
                XmlSerializer taskSerializer = new XmlSerializer(taskValidator.ValidatorType);

                // get embedded schema resource stream
                Stream schemaStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    taskValidator.ValidatorType.Namespace);

                // ensure schema resource was embedded
                if (schemaStream == null) {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                        "Schema resource '{0}' could not be found.",
                        taskValidator.ValidatorType.Namespace), Location);
                }

                // load schema resource
                XmlTextReader tr = new XmlTextReader(
                    schemaStream, XmlNodeType.Element, null);

                // Add the schema to a schema collection
                XmlSchema schema = XmlSchema.Read(tr, null);
                XmlSchemaCollection schemas = new XmlSchemaCollection();
                schemas.Add(schema);

                string xmlNamespace = (taskValidator.XmlNamespace != null ? taskValidator.XmlNamespace : GetType().FullName);

                // Create a namespace manager with the schema's namespace
                NameTable nt = new NameTable();
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
                nsmgr.AddNamespace(string.Empty, xmlNamespace);

                // Create a textreader containing just the Task's Node
                XmlParserContext ctx = new XmlParserContext(
                    null, nsmgr, null, XmlSpace.None);
                taskXml.SetAttribute("xmlns", xmlNamespace);
                XmlTextReader textReader = new XmlTextReader(taskXml.OuterXml,
                    XmlNodeType.Element, ctx);

                // Copy the node from the TextReader and indent it (for error
                // reporting, since NAnt does not retain formatting during a load)
                StringWriter stringWriter = new StringWriter();
                XmlTextWriter textWriter = new XmlTextWriter(stringWriter);
                textWriter.Formatting = Formatting.Indented;

                textWriter.WriteNode(textReader, true);

                //textWriter.Close();
                XmlTextReader formattedTextReader = new XmlTextReader(
                    stringWriter.ToString(), XmlNodeType.Document, ctx);

                // Validate the Task's XML against its schema
                XmlValidatingReader validatingReader = new XmlValidatingReader(
                    formattedTextReader);
                validatingReader.ValidationType = ValidationType.Schema;
                validatingReader.Schemas.Add(schemas);
                validatingReader.ValidationEventHandler +=
                    new ValidationEventHandler(Task_OnSchemaValidate);

                while (validatingReader.Read()) {
                    // Read strictly for validation purposes
                }
                validatingReader.Close();

                if (!_validated) {
                    // Log any validation errors that have ocurred
                    for (int i = 0; i < _validationExceptions.Count; i++) {
                        BuildException ve = (BuildException) _validationExceptions[i];
                        if (i == _validationExceptions.Count - 1) {
                            // If this is the last validation error, throw it
                            throw ve;
                        }
                        Log(Level.Info, ve.Message);
                    }
                }

                NameTable taskNameTable = new NameTable();
                XmlNamespaceManager taskNSMgr = new XmlNamespaceManager(taskNameTable);
                taskNSMgr.AddNamespace(string.Empty, xmlNamespace);

                XmlParserContext context = new XmlParserContext(
                    null, taskNSMgr, null, XmlSpace.None);

                XmlTextReader taskSchemaReader = new XmlTextReader(
                    taskXml.OuterXml, XmlNodeType.Element, context);

                // Deserialize from the Task's XML to the schema wrapper object
                _schemaObject = taskSerializer.Deserialize(taskSchemaReader);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Validate the document against the standard WiX schema and any extensions.
        /// </summary>
        /// <param name="document">The xml document to validate.</param>
        private void ValidateDocument(XmlDocument document)
        {
            // if we haven't loaded the schemas yet, do that now
            if (null == this.schemas)
            {
                this.schemas = new XmlSchemaCollection();

                // always add the WiX schema first
                this.schemas.Add(this.schema);

                // add all the extension schemas
                foreach (CompilerExtension compilerExtension in this.extensions.Values)
                {
                    this.schemas.Add(compilerExtension.Schema);
                }
            }

            // write the document to a string for validation
            StringWriter xml = new StringWriter(CultureInfo.InvariantCulture);
            XmlTextWriter writer = null;
            try
            {
                writer = new XmlTextWriter(xml);
                document.WriteTo(writer);
            }
            finally
            {
                if (null != writer)
                {
                    writer.Close();
                }
            }

            // validate the xml string (and thus the document)
            SourceLineNumberCollection sourceLineNumbers = null;
            XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.None);
            XmlValidatingReader validatingReader = null;
            try
            {
                validatingReader = new XmlValidatingReader(xml.ToString(), XmlNodeType.Document, context);
                validatingReader.Schemas.Add(this.schemas);

                while (validatingReader.Read())
                {
                    if (XmlNodeType.ProcessingInstruction == validatingReader.NodeType && Preprocessor.LineNumberElementName == validatingReader.Name)
                    {
                        sourceLineNumbers = new SourceLineNumberCollection(validatingReader.Value);
                    }
                }
            }
            catch (XmlSchemaException e)
            {
                string message = e.Message.Replace(String.Concat(this.schema.TargetNamespace, ":"), String.Empty);

                this.core.OnMessage(WixErrors.SchemaValidationFailed(sourceLineNumbers, message, e.LineNumber, e.LinePosition));
            }
            finally
            {
                if (null != validatingReader)
                {
                    validatingReader.Close();
                }
            }
        }
Esempio n. 26
0
        private bool IsValidXml(string message)
        {
            if (Regex.Match(message, @"^<.*>").Success) {
                XmlValidatingReader reader = null;

                try {
                    // validate xml
                    reader = new XmlValidatingReader(message,
                        XmlNodeType.Document, null);

                    while (reader.Read()) {
                    }

                    // the xml is valid
                    return true;
                } catch {
                    return false;
                } finally {
                    if (reader != null) {
                        reader.Close();
                    }
                }
            }
            return false;
        }
Esempio n. 27
0
		static private XmlDocument OpenDocument( string IncludeFilePath ) 
		{
			XmlValidatingReader reader = new XmlValidatingReader( new XmlTextReader( IncludeFilePath ) );
			reader.ValidationType = ValidationType.None;
			reader.XmlResolver = null;		

			XmlDocument doc = new XmlDocument();
			doc.Load( reader );
			reader.Close();			//make sure we close the reader before saving

			return doc;
		}
 /// <include file='doc\WebReferenceOptions.uex' path='docs/doc[@for="XmlSchema.Read2"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public static WebReferenceOptions Read(XmlReader xmlReader, ValidationEventHandler validationEventHandler) {
     XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader);
     validatingReader.ValidationType = ValidationType.Schema;
     if (validationEventHandler != null) {
         validatingReader.ValidationEventHandler += validationEventHandler;
     }
     else {
         validatingReader.ValidationEventHandler += new ValidationEventHandler(SchemaValidationHandler);
     }
     validatingReader.Schemas.Add(Schema);
     webReferenceOptionsSerializer ser = new webReferenceOptionsSerializer();
     try {
         return (WebReferenceOptions)ser.Deserialize(validatingReader);
     }
     catch (Exception e) {
         throw e;
     }
     finally {
         validatingReader.Close();
     }
 }
	    private void ValidateXmlIfNeeded(string xml)
	    {
            if (validateXml)
            {
                // stream to validate
                using (StringReader stringReader = new StringReader(xml))
                {
                    XmlTextReader xmlr = new XmlTextReader(stringReader);
                    XmlValidatingReader xmlvread = new XmlValidatingReader(xmlr);

                    // Set the validation event handler
                    xmlvread.ValidationEventHandler += new ValidationEventHandler(XmlValidationCallBack);

                    // Read XML data
                    while (xmlvread.Read()) { }

                    //Close the reader.
                    xmlvread.Close();
                }
            }
	    }
Esempio n. 30
0
 private void ParseDocumentType ( XmlDocumentType dtNode, bool bUseResolver, XmlResolver resolver ) {
     this.doc = dtNode.OwnerDocument;
     XmlNameTable nt = this.doc.NameTable;
     XmlNamespaceManager mgr = new XmlNamespaceManager( nt );
     XmlParserContext pc = new XmlParserContext( nt,
                                                 mgr,
                                                 dtNode.Name,
                                                 dtNode.PublicId,
                                                 dtNode.SystemId,
                                                 dtNode.InternalSubset,
                                                 this.doc.BaseURI,
                                                 String.Empty,
                                                 XmlSpace.None
                                                 );
     XmlValidatingReader vr = new XmlValidatingReader( "", XmlNodeType.Element, pc );
     vr.Namespaces = dtNode.ParseWithNamespaces;
     if ( bUseResolver )
         vr.XmlResolver = resolver;
     vr.ValidationType = ValidationType.None;
     vr.Read();
     LoadDocumentType( vr, dtNode );
     vr.Close();
 }
Esempio n. 31
0
        /// <SUMMARY>
        /// This method validates an xml string against an xml schema.
        /// </SUMMARY>
        /// <PARAM name="xml">StringReader containing xml</PARAM>
        /// <PARAM name="schemaNamespace">XML Schema Namespace</PARAM>
        /// <PARAM name="schemaUri">XML Schema Uri</PARAM>
        /// <RETURNS>bool</RETURNS>
        public bool ValidXmlDoc(StringReader xml,
                                string schemaNamespace, string schemaUri)
        {
            // Continue?
            if (xml == null || schemaNamespace == null || schemaUri == null)
            {
                return false;
            }

            isValidXml = true;
            XmlValidatingReader vr;
            XmlTextReader tr;
            var schemaCol = new XmlSchemaCollection();
            schemaCol.Add(schemaNamespace, schemaUri);

            try
            {
                // Read the xml.
                tr = new XmlTextReader(xml);
                // Create the validator.
                vr = new XmlValidatingReader(tr);
                // Set the validation tyep.
                vr.ValidationType = ValidationType.Auto;
                // Add the schema.
                if (schemaCol != null)
                {
                    vr.Schemas.Add(schemaCol);
                }
                // Set the validation event handler.
                vr.ValidationEventHandler +=
                    ValidationCallBack;
                // Read the xml schema.
                while (vr.Read())
                {
                }

                vr.Close();

                return isValidXml;
            }
            catch (Exception ex)
            {
                ValidationError = ex.Message;
                return false;
            }
            finally
            {
                // Clean up...
                vr = null;
                tr = null;
            }
        }