static XmlReader CreateValidatingReader (Stream stream, XmlSchemaCollection schemas, ValidationEventHandler eventHandler) { XmlValidatingReader reader = new XmlValidatingReader (new XmlTextReader (stream)); reader.Schemas.Add (schemas); reader.ValidationType = ValidationType.Schema; if (eventHandler != null) reader.ValidationEventHandler += eventHandler; return reader; }
static void Main () { string dir = AppDomain.CurrentDomain.BaseDirectory; using (Stream input = File.OpenRead (Path.Combine (dir, "test.xml"))) { #if NET_2_0 XmlSchemaSet schemas = new XmlSchemaSet (); #else XmlSchemaCollection schemas = new XmlSchemaCollection (); #endif schemas.Add (XmlSchema.Read (File.OpenRead (Path.Combine (dir, "spring-objects.xsd")), null)); XmlReader reader = CreateValidatingReader (input, schemas, null); XmlDocument doc = new XmlDocument (); doc.Load (reader); } }
protected void cmdValidate_Click(object sender, EventArgs e) { string filePath = ""; if (optValid.Checked) { filePath = Server.MapPath("DvdList.xml"); } else if (optInvalidData.Checked) { filePath += Server.MapPath("DvdListInvalid.xml"); } lblStatus.Text = ""; // Open the XML file. FileStream fs = new FileStream(filePath, FileMode.Open); XmlTextReader r = new XmlTextReader(fs); // Create the validating reader. XmlValidatingReader vr = new XmlValidatingReader(r); vr.ValidationType = ValidationType.Schema; // Add the XSD file to the validator. XmlSchemaCollection schemas = new XmlSchemaCollection(); schemas.Add("", Server.MapPath("DvdList.xsd")); vr.Schemas.Add(schemas); // Connect the event handler. vr.ValidationEventHandler += new ValidationEventHandler(MyValidateHandler); // Read through the document. while (vr.Read()) { // Process document here. // If an error is found, an exception will be thrown. } vr.Close(); lblStatus.Text += "<br>Complete."; }
/// <summary> /// Gets an appropriate <see cref="System.Xml.XmlReader"/> implementation /// for the supplied <see cref="System.IO.Stream"/>. /// </summary> /// <param name="stream">The XML <see cref="System.IO.Stream"/> that is going to be read.</param> /// <param name="xmlResolver"><see cref="XmlResolver"/> to be used for resolving external references</param> /// <param name="schemas">XML schemas that should be used for validation.</param> /// <param name="eventHandler">Validation event handler.</param> /// <returns> /// A validating <see cref="System.Xml.XmlReader"/> implementation. /// </returns> public static XmlReader CreateValidatingReader(Stream stream, XmlResolver xmlResolver, XmlSchemaCollection schemas, ValidationEventHandler eventHandler) { XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(stream)); reader.XmlResolver = xmlResolver; reader.Schemas.Add(schemas); reader.ValidationType = ValidationType.Schema; if (eventHandler != null) { reader.ValidationEventHandler += eventHandler; } return(reader); }
/// <summary> /// Run the application with the given arguments. /// </summary> /// <param name="args">The commandline arguments.</param> /// <returns>The number of errors that were found.</returns> private int Run(string[] args) { XmlSchema mainSchema = null; XmlSchemaCollection schemas = new XmlSchemaCollection(); try { this.ParseCommandLine(args); if (this.showLogo) { Assembly thisAssembly = Assembly.GetExecutingAssembly(); Console.WriteLine("Microsoft (R) Windows Installer Xsd Stitch version {0}", thisAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2006. All rights reserved."); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: xsdStitch.exe mainSchema.xsd stitched.xsd"); Console.WriteLine(); Console.WriteLine(" -ext extSchema.xsd adds an extension schema to the main schema"); Console.WriteLine(" -nologo suppress displaying the logo information"); Console.WriteLine(" -? this help information"); Console.WriteLine(); return(0); } XmlTextReader mainSchemaReader = null; // load the main schema try { mainSchemaReader = new XmlTextReader(this.mainSchemaFile); mainSchema = XmlSchema.Read(mainSchemaReader, null); schemas.Add(mainSchema); } finally { if (null != mainSchemaReader) { mainSchemaReader.Close(); } } StringCollection addedSchemas = new StringCollection(); // load the extension schemas foreach (string extensionSchemaFile in this.extensionSchemaFiles) { XmlTextReader reader = null; try { string schemaFilename = Path.GetFileNameWithoutExtension(extensionSchemaFile); if (addedSchemas.Contains(schemaFilename)) { int duplicateNameCounter = 2; while (addedSchemas.Contains(String.Concat(schemaFilename, duplicateNameCounter))) { duplicateNameCounter++; } schemaFilename = String.Concat(schemaFilename, duplicateNameCounter); } addedSchemas.Add(schemaFilename); reader = new XmlTextReader(extensionSchemaFile); XmlSchema extensionSchema = XmlSchema.Read(reader, null); mainSchema.Namespaces.Add(schemaFilename, extensionSchema.TargetNamespace); schemas.Add(extensionSchema); // add an import for the extension schema XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = extensionSchema.TargetNamespace; import.SchemaLocation = Path.GetFileName(extensionSchemaFile); mainSchema.Includes.Add(import); } finally { if (null != reader) { reader.Close(); } } } foreach (XmlSchema schema in schemas) { if (schema != mainSchema) { foreach (XmlSchemaElement element in schema.Elements.Values) { // retrieve explicitly-specified parent elements if (element.Annotation != null) { foreach (XmlSchemaObject obj in element.Annotation.Items) { XmlSchemaAppInfo appInfo = obj as XmlSchemaAppInfo; if (appInfo != null) { foreach (XmlNode node in appInfo.Markup) { XmlElement markupElement = node as XmlElement; if (markupElement != null && markupElement.LocalName == "parent" && markupElement.NamespaceURI == XmlSchemaExtensionNamespace) { string parentNamespace = markupElement.GetAttribute("namespace"); string parentRef = markupElement.GetAttribute("ref"); if (parentNamespace.Length == 0) { throw new ApplicationException("The parent element is missing the namespace attribute."); } if (parentRef.Length == 0) { throw new ApplicationException("The parent element is missing the ref attribute."); } XmlQualifiedName parentQualifiedName = new XmlQualifiedName(parentRef, parentNamespace); XmlSchemaElement parentElement = (XmlSchemaElement)mainSchema.Elements[parentQualifiedName]; XmlSchemaComplexType complexType = (XmlSchemaComplexType)parentElement.ElementType; if (complexType.Particle != null) { XmlSchemaElement elementRef = new XmlSchemaElement(); elementRef.RefName = element.QualifiedName; this.InsertElement(complexType.Particle, elementRef); } } } } } } } foreach (XmlSchemaAttribute attribute in schema.Attributes.Values) { if (attribute.Annotation != null) { foreach (XmlSchemaObject obj in attribute.Annotation.Items) { XmlSchemaAppInfo appInfo = obj as XmlSchemaAppInfo; if (appInfo != null) { foreach (XmlNode node in appInfo.Markup) { XmlElement markupElement = node as XmlElement; if (markupElement != null && markupElement.LocalName == "parent" && markupElement.NamespaceURI == XmlSchemaExtensionNamespace) { string parentNamespace = markupElement.GetAttribute("namespace"); string parentRef = markupElement.GetAttribute("ref"); if (parentNamespace.Length == 0) { throw new ApplicationException("The parent element is missing the namespace attribute."); } if (parentRef.Length == 0) { throw new ApplicationException("The parent element is missing the ref attribute."); } XmlQualifiedName parentQualifiedName = new XmlQualifiedName(parentRef, parentNamespace); XmlSchemaElement parentElement = (XmlSchemaElement)mainSchema.Elements[parentQualifiedName]; XmlSchemaComplexType complexType = (XmlSchemaComplexType)parentElement.ElementType; if (complexType.Particle != null) { XmlSchemaAttribute attributeRef = new XmlSchemaAttribute(); attributeRef.RefName = attribute.QualifiedName; anyAttributeElements.Add(complexType); complexType.Attributes.Add(attribute); } } } } } } } } } // remove the any items foreach (DictionaryEntry entry in this.anys) { XmlSchemaAny any = (XmlSchemaAny)entry.Key; XmlSchemaParticle particle = (XmlSchemaParticle)entry.Value; if (particle is XmlSchemaChoice) { XmlSchemaChoice choice = (XmlSchemaChoice)particle; choice.Items.Remove(any); } else if (particle is XmlSchemaSequence) { XmlSchemaSequence sequence = (XmlSchemaSequence)particle; sequence.Items.Remove(any); } } // remove anyAttribute items foreach (XmlSchemaComplexType complexType in this.anyAttributeElements) { complexType.AnyAttribute = null; } XmlTextWriter writer = null; try { writer = new XmlTextWriter(this.outputFile, System.Text.Encoding.Default); writer.Indentation = 4; writer.IndentChar = ' '; writer.Formatting = Formatting.Indented; mainSchema.Write(writer); } finally { writer.Close(); } } catch (Exception e) { Console.WriteLine("xsdStitch.exe : fatal error XSDS0001 : {0}\r\n\n\nStack Trace:\r\n{1}", e.Message, e.StackTrace); return(1); } return(0); }
private void ReadXML() { double RelayDelay; DateTime date; string IP; MODE mode; decimal TZ_Offset; string Pword; try { //open up a stream and fed it to the XmlTextReader StreamReader sRdr = new StreamReader(XMLfname); XmlTextReader tRdr = new XmlTextReader(sRdr); //Instantiate a new schemas collection //Add this one schema to the collection //A collection means that you can validate this XML file against any //number of schemas. You would do this if you were reading the file //piecemeal XmlSchemaCollection Schemas = new XmlSchemaCollection(); Schemas.Add(null, XSDfname); //Instantiate a new validating reader. This validates for data type //and presence. //Add the schemas collection to the validating reader and funnel the //XmlTextReader through it. //wire up an ad-hoc validation delegate to catch any validation errors XmlValidatingReader vRdr = new XmlValidatingReader(tRdr); vRdr.ValidationType = ValidationType.Schema; vRdr.ValidationEventHandler += new ValidationEventHandler(ValXML); vRdr.Schemas.Add(Schemas); //Read the XML file through the validator object node; while (vRdr.Read()) { node = null; if (vRdr.LocalName.Equals("ConfigDate")) { node = vRdr.ReadTypedValue(); if (node != null) { date = (DateTime)node; } } if (vRdr.LocalName.Equals("RelayDelay")) { node = vRdr.ReadTypedValue(); if (node != null) { RelayDelay = (double)node; } } if (vRdr.LocalName.Equals("TimeZoneOffset")) { node = vRdr.ReadTypedValue(); if (node != null) { TZ_Offset = (decimal)node; } } if (vRdr.LocalName.Equals("PassWord")) { node = vRdr.ReadTypedValue(); if (node != null) { Pword = (string)node; } } if (vRdr.LocalName.Equals("Mode")) { node = vRdr.ReadTypedValue(); // mode = (string)node; } if (vRdr.LocalName.Equals("IP")) { node = vRdr.ReadTypedValue(); if (node != null) { IP = (string)node; } } if (node != null) { rcResults.AppendText(vRdr.LocalName + "\n"); rcResults.AppendText(node.GetType().ToString() + "\n"); rcResults.AppendText(node.ToString() + "\n\n"); } } vRdr.Close(); tRdr.Close(); sRdr.Close(); } catch (Exception e) { //The handler will catch mal-formed xml docs. //It is not intended to catch bad data. That is the delegates job MessageBox.Show("Exception analyzing Config file: " + e.Message); } }
private static void Main(string[] args) { // コマンドライン引数をパースする string scriptPath = null; string configPath = null; for (int i = 0; i < args.Length; ++i) { if ((string.Compare(args[i], "-s", true) == 0) && (i + 1 < args.Length)) { scriptPath = args[i + 1]; } else if ((string.Compare(args[i], "-c", true) == 0) && (i + 1 < args.Length)) { configPath = args[i + 1]; } } // スクリプトの指定がない場合はエラー if (scriptPath == null) { MessageBox.Show("Please specify a script to set a command line argument."); return; } // XML設定ファイルをパースする referenceAssembly reference = null; if (configPath != null) { Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream ("Kodama.BootLoader.Schema.AssemblyConfig.xsd"); XmlSchemaCollection schema = new XmlSchemaCollection(); schema.Add(null, new XmlTextReader(stream)); XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(configPath)); reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(schema); XmlSerializer serializer = new XmlSerializer(typeof(referenceAssembly)); try { reference = (referenceAssembly)serializer.Deserialize(reader); } finally { reader.Close(); } } // スクリプトエンジンを作成し、スクリプトを呼び出す IScriptEngineFactory[] factories = new IScriptEngineFactory[] { new CSharpScriptEngineFactory(), new JScriptEngineFactory(), new VBScriptEngineFactory() }; foreach (IScriptEngineFactory factory in factories) { // サポートしているフォーマットかチェックする if (!factory.CanCompile(scriptPath)) { continue; } // スクリプトエンジンの作成 IScriptEngine engine = factory.CreateFromFile(scriptPath); // XMLファイルに書かれていたアセンブリの参照を設定する if (reference != null) { foreach (referenceAssemblyAssembly assembly in reference.Items) { engine.AddReference(assembly.name); } } // コンパイルする try { engine.Compile(); } catch (CompileErrorException e) { StringBuilder errors = new StringBuilder(10000); foreach (CompileErrorInfo cei in e.GetCompileErrorInfos()) { errors.Append("--------------------------------" + "\n"); errors.Append("SourceName : " + cei.SourceName + "\n"); errors.Append("Description : " + cei.Description + "\n"); errors.Append("Line : " + cei.ErrorLine + "\n"); errors.Append("Code : " + cei.ErrorText + "\n"); errors.Append("--------------------------------" + "\n"); } engine.Close(); MessageBox.Show("The error occurred in compile of the script.\n" + errors.ToString()); return; } // スクリプトを実行する try { engine.Run(); } catch (ScriptEntryPointNotFoundException) { engine.Close(); MessageBox.Show("An entry point is not found in the script."); } // エンジンを閉じる engine.Close(); return; } MessageBox.Show("It is the format of the script which is not supported."); }
/// <summary> /// Main entry point for sample application. /// </summary> /// <param name="args"></param> public static void Main(string[] args) { XmlSchema myXmlSchema; XmlTextWriter myXmlTextWriter; try { Console.WriteLine("Creating Schema in the Schema Object Model..."); // Setup console output. myXmlTextWriter = new XmlTextWriter(Console.Out); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.Indentation = 2; //Create an XmlNameTable. XmlNameTable myXmlNameTable = new NameTable(); //Add the nametable to the XmlSchemaCollection. XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection(myXmlNameTable); //Add some schemas to the XmlSchemaCollection. Console.WriteLine("Reading and adding {0} schema.", BOOKSCHEMA); myXmlSchemaCollection.Add(null, BOOKSCHEMA); Console.WriteLine("Reading and adding {0} schema.", POSCHEMA); myXmlSchemaCollection.Add(null, POSCHEMA); Console.WriteLine("Added schemas successfully ..."); Console.WriteLine("Showing added schemas"); foreach (XmlSchema myTempXmlSchema in myXmlSchemaCollection) { myXmlSchema = myTempXmlSchema; Console.WriteLine(); string outfile = myTempXmlSchema.SourceUri.Replace("file:///", ""); Console.WriteLine("Schema from: {0}", outfile); Console.WriteLine(); Console.WriteLine("=== Start of Schema ==="); Console.WriteLine(); // Write out the various schema parts WriteXSDSchema(myXmlSchema, myXmlTextWriter); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("=== End of Schema ==="); Console.WriteLine(); Console.WriteLine("Example of possible XML contents for: {0}", outfile); Console.WriteLine(); Console.WriteLine("=== Start of Example ==="); // Write out an example of the XML for the schema WriteExample(myXmlSchema, myXmlTextWriter); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("=== End of Example ==="); } //foreach } //try catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } //catch } //Main()
/// <summary> /// Adds a set of XML Schemas to the collection to use for validation. /// </summary> public void AddSchemas(XmlSchemaCollection schemas) { _xmlschemas.Add(schemas); }
/// <summary> /// Run the application. /// </summary> /// <param name="args">The command line arguments.</param> /// <returns>The error code for the application.</returns> private int Run(string[] args) { try { this.ParseCommandline(args); // get the assemblies Assembly docCompilerAssembly = Assembly.GetExecutingAssembly(); if (this.showHelp) { Console.WriteLine("Microsoft (R) Documentation Compiler version {0}", docCompilerAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation. All rights reserved."); Console.WriteLine(); Console.WriteLine(" usage: DocCompiler [-?] [-c:hhc.exe | -w] [-v version] tableOfContents.xml output"); Console.WriteLine(); Console.WriteLine(" c - path to HTML Help Compiler to create output CHM"); Console.WriteLine(" w - creates Web HTML Manual to output directory"); Console.WriteLine(" -v set version information for elements"); return(0); } // ensure the directory containing the html files exists Directory.CreateDirectory(Path.Combine(this.outputDir, "html")); // load the schema XmlReader schemaReader = null; XmlSchemaCollection schemas = null; try { schemaReader = new XmlTextReader(docCompilerAssembly.GetManifestResourceStream("Microsoft.Tools.DocCompiler.Xsd.docCompiler.xsd")); schemas = new XmlSchemaCollection(); schemas.Add(DocCompilerNamespace, schemaReader); } finally { schemaReader.Close(); } // load the table of contents XmlTextReader reader = null; try { reader = new XmlTextReader(this.tocFile); XmlValidatingReader validatingReader = new XmlValidatingReader(reader); validatingReader.Schemas.Add(schemas); // load the xml into a DOM XmlDocument doc = new XmlDocument(); doc.Load(validatingReader); // create a namespace manager this.namespaceManager = new XmlNamespaceManager(doc.NameTable); this.namespaceManager.AddNamespace("doc", DocCompilerNamespace); this.namespaceManager.PushScope(); this.ProcessCopyFiles(doc); this.ProcessTopics(doc); this.ProcessSchemas(doc); if (this.chm) { this.CompileChm(doc); } if (this.web) { this.BuildWeb(doc); } } finally { if (reader != null) { reader.Close(); } } } catch (Exception e) { Console.WriteLine("DocCompiler.exe : fatal error DCMP0001: {0}", e.Message); Console.WriteLine(); Console.WriteLine("Stack Trace:"); Console.WriteLine(e.StackTrace); if (e is NullReferenceException) { throw; } return(1); } return(0); }
/// <summary> /// 运行函数,参数1为SLD结果路径,参数2为模板文件名 /// </summary> /// <param name="args"></param> public void Run(string[] args) { XmlValidatingReader reader = null; XmlSchemaCollection xsc = new XmlSchemaCollection(); try { xsc.Add(null, new XmlTextReader(args[1])); reader = new XmlValidatingReader(new XmlTextReader(args[0])); IXmlLineInfo lineInfo = (IXmlLineInfo)reader; ValidationEventHandler valdel = new ValidationEventHandler(ValidationEvent); reader.ValidationEventHandler += valdel; reader.Schemas.Add(xsc); reader.ValidationType = ValidationType.Schema; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { while (reader.MoveToNextAttribute()) { m_iLinenumber = Convert.ToInt16(lineInfo.LineNumber.ToString()); m_cNodePosition = lineInfo.LinePosition.ToString(); m_cNodeType = reader.NodeType.ToString(); m_cNodeName = reader.Name.ToString(); } } } } catch (XmlSchemaException e) { m_cValidatMessage = m_cValidatMessage + "XML 模板错误" + "\r\n" + "\r\n"; m_cValidatMessage = m_cValidatMessage + "加载的XML不可用 " + "\r\n" + "后语为加载正确的命名空间, 错误信息: " + "\r\n" + e.Message + "\r\n" + "行: " + Convert.ToString(e.LinePosition) + "\r\n"; m_cValidatMessage = m_cValidatMessage + "\r\n" + "\r\n"; m_bValid = false; } catch (XmlException e) { m_cValidatMessage = m_cValidatMessage + "XML-SYNTAX EXCEPTION!" + "\r\n" + "\r\n"; m_cValidatMessage = m_cValidatMessage + "the file comprises an XML-Syntax error. " + "\r\n" + e.Message; m_cValidatMessage = m_cValidatMessage + "\r\n" + "\r\n"; m_bValid = false; } catch (Exception e) { m_cValidatMessage = m_cValidatMessage + "SERIOUS EXCEPTION!" + "\r\n" + "\r\n"; m_cValidatMessage = m_cValidatMessage + "Unknown error while validating SLD" + "\r\n" + e.Message; m_cValidatMessage = m_cValidatMessage + e.StackTrace + "\r\n"; m_cValidatMessage = m_cValidatMessage + "\r\n" + "\r\n"; m_bValid = false; } finally { if (!(reader == null)) { reader.Close(); } } }
/// <summary> /// Initializes the task and verifies parameters. /// </summary> protected override void Initialize() { XmlElement taskXml = (XmlElement)XmlNode.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 = this.PropertyAccessor.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); } }
/// <summary> /// Validates the XML file against a specified Schema file. /// </summary> /// <returns>A ValidXML struct.<see cref="ValidXML"/></returns> public ValidXML Validate() { XmlTextReader xml = null; XmlValidatingReader xsd = null; try { //1. Set the this.m_objValidationResult.IsValid = true; // Create the XML text reader object. xml = new XmlTextReader(this.m_strXMLFile); // Create a validating reader object. xsd = new XmlValidatingReader(xml); // Load the Schema collection. XmlSchemaCollection xsc = new XmlSchemaCollection(); xsc.Add(this.m_strNameSpace, this.m_strXSDFile); // Validate using the schemas stored in the schema collection. xsd.Schemas.Add(xsc); // Set the validation type. xsd.ValidationType = ValidationType.Schema; // Set the validation event handler. xsd.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler); // Read and validate the XML data. while (xsd.Read()) { } } catch (XmlException ex) { // Set the IsValid property to false. this.m_objValidationResult.IsValid = false; // Set the Error details. this.m_objValidationResult.Error += "Message: " + ex.Message; } catch (Exception ex) { throw new ApplicationException(ex.Message); } //Close xml reader even if there is exception //This fixes the following bug: //If a xml file is not valid, and exception is throwed. this file is locked, no more file can be uploaded //Jack Liu 15/09/2005, finally { if (xsd != null) { xsd.Close(); } if (xml != null) { xml.Close(); } } return(this.m_objValidationResult); }
public static IDocumentPlug CreateDocumentPlugFromXmlSchema(XmlSchemaCollection collection, string targetNamespace, string name) { IDocumentPlug plug = XmlSchemaHelper.CreateDocumentPlug(collection, targetNamespace, name); return(plug); }
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(); }
/// <summary> /// Validates XML against a schema. /// </summary> /// <param name="xml">XML to validate.</param> /// <param name="shortCircuit"> /// Defines validation behaviour should invalid XML be encountered. Setting to a type other than None /// forces the validation process to immedietely quit according to the type of problem encountered. /// </param> /// <returns>Result as ValidatorResultType. Extra information can be extracted from Warnings and Errors properties.</returns> /// <overloaded/> public ValidatorResultType Validate(string xml, ValidatorShortCircuitType shortCircuit) { // NB overloaded //validate arguments if (xml == null) { throw new ArgumentNullException("xml"); } else if (xml.Length == 0) { throw new ArgumentOutOfRangeException("xml"); } //initialise variables m_warnings = null; m_errors = null; m_result = ValidatorResultType.Valid; try { //load the xml into validating reader XmlValidatingReader xmlValidatingReader = null; //configure validating reader and schema(s) according to schema type if (m_validationType == ValidationType.Schema) { //if the XSD schema collection is not yet prepared, do so now if (!m_isSchemaCollectionPrepared) { //prepare the additional resources resolver with all of the extra XSD's PrepareResourceResolver(); //load main XSD into schemas collection m_schemas = new XmlSchemaCollection(); m_schemas.Add(null, GetXmlTextReader(m_schema), m_additionalResourceResolver); //flag that we have already prepared the schemas to improve //performance on subsequent validation requests m_isSchemaCollectionPrepared = true; } //create the validating reader and assign schemas xmlValidatingReader = new XmlValidatingReader(GetXmlTextReader(xml)); xmlValidatingReader.ValidationType = ValidationType.Schema; xmlValidatingReader.Schemas.Add(m_schemas); } else { //set up validating reader for DTD XmlParserContext context = new XmlParserContext(null, null, m_dtdDocTypeName, null, null, m_schema, "", "", XmlSpace.None); xmlValidatingReader = new XmlValidatingReader(xml, XmlNodeType.Element, context); xmlValidatingReader.ValidationType = ValidationType.DTD; xmlValidatingReader.EntityHandling = EntityHandling.ExpandCharEntities; } //assign event handler which will receive validation errors xmlValidatingReader.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); //read the xml to perform validation try { while (xmlValidatingReader.Read()) { //check if we need to quit if (shortCircuit == ValidatorShortCircuitType.OnWarning && (m_result == ValidatorResultType.ValidWithWarnings || m_result == ValidatorResultType.InValid)) { break; } else if (shortCircuit == ValidatorShortCircuitType.OnError && m_result == ValidatorResultType.InValid) { break; } } } catch (Exception exc) { //xml form error AddToArrayList(ref m_errors, exc.Message); m_result = ValidatorResultType.InValid; } return(m_result); } catch (Exception exc) { throw exc; } }
public void Create() { if (!this.ServiceBroker.MessageTypes.Contains(this.FullName)) { // Create message types MessageType msgType = new MessageType( this.ServiceBroker, this.FullName); msgType.MessageTypeValidation = this.MessageTypeValidation; if (msgType.MessageTypeValidation == MessageTypeValidation.XmlSchemaCollection) { if(!this.ServiceBroker.Parent.XmlSchemaCollections.Contains (this.ValidationXmlSchemaCollection) && ! String.IsNullOrEmpty(this.ValidationXmlSchemaCollectionSchema)) { XmlSchemaCollection schema = new XmlSchemaCollection (this.ServiceBroker.Parent, this.ValidationXmlSchemaCollection); schema.Text = this.ValidationXmlSchemaCollectionSchema; schema.Create(); } msgType.ValidationXmlSchemaCollection = this.ValidationXmlSchemaCollection; } msgType.Create(); } }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { int beginTickCount = Environment.TickCount; try { this.tempFileCollection = new TempFileCollection(); Environment.SetEnvironmentVariable("WixUnitTempDir", this.tempFileCollection.BasePath, EnvironmentVariableTarget.Process); this.ParseCommandline(args); // get the assemblies Assembly wixUnitAssembly = this.GetType().Assembly; FileVersionInfo fv = FileVersionInfo.GetVersionInfo(wixUnitAssembly.Location); if (this.showHelp) { Console.WriteLine("WixUnit version {0}", fv.FileVersion); Console.WriteLine("Copyright (C) Outercurve Foundation. All rights reserved."); Console.WriteLine(); Console.WriteLine(" usage: WixUnit [-?] tests.xml"); Console.WriteLine(); Console.WriteLine(" -env:<var>=<value> Sets an environment variable to the value for the current process"); Console.WriteLine(" -notidy Do not delete temporary files (for checking results)"); Console.WriteLine(" -rf Re-run the failed test from the last run"); Console.WriteLine(" -st Run the tests on a single thread"); Console.WriteLine(" -test:<Test_name> Run only the specified test (may use wildcards)"); Console.WriteLine(" -update Prompt user to auto-update a test if expected and actual output files do not match"); Console.WriteLine(" -v Verbose output"); Console.WriteLine(" -val Run MSI validation for light unit tests"); return(0); } // set the environment variables for the process only foreach (KeyValuePair <string, string> environmentVariable in this.environmentVariables) { Environment.SetEnvironmentVariable(environmentVariable.Key, environmentVariable.Value, EnvironmentVariableTarget.Process); } // load the schema XmlReader schemaReader = null; XmlSchemaCollection schemas = null; try { schemas = new XmlSchemaCollection(); schemaReader = new XmlTextReader(wixUnitAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Unit.unitTests.xsd")); XmlSchema schema = XmlSchema.Read(schemaReader, null); schemas.Add(schema); } finally { if (schemaReader != null) { schemaReader.Close(); } } // load the unit tests XmlTextReader reader = null; XmlDocument doc = new XmlDocument(); try { reader = new XmlTextReader(this.unitTestsFile); XmlValidatingReader validatingReader = new XmlValidatingReader(reader); validatingReader.Schemas.Add(schemas); // load the xml into a DOM doc.Load(validatingReader); } catch (XmlException e) { SourceLineNumber sourceLineNumber = new SourceLineNumber(this.unitTestsFile, e.LineNumber); SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber }); throw new WixException(WixErrors.InvalidXml(sourceLineNumbers, "unitTests", e.Message)); } catch (XmlSchemaException e) { SourceLineNumber sourceLineNumber = new SourceLineNumber(this.unitTestsFile, e.LineNumber); SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber }); throw new WixException(WixErrors.SchemaValidationFailed(sourceLineNumbers, e.Message, e.LineNumber, e.LinePosition)); } finally { if (reader != null) { reader.Close(); } } // check the document element if ("UnitTests" != doc.DocumentElement.LocalName || XmlNamespace != doc.DocumentElement.NamespaceURI) { throw new InvalidOperationException("Unrecognized document element."); } // create a regular expression of the selected tests Regex selectedUnitTests = new Regex(String.Concat("^", String.Join("$|^", (string[])this.unitTests.ToArray(typeof(string))), "$"), RegexOptions.IgnoreCase | RegexOptions.Singleline); // find the unit tests foreach (XmlNode node in doc.DocumentElement) { if (XmlNodeType.Element == node.NodeType) { switch (node.LocalName) { case "UnitTest": XmlElement unitTestElement = (XmlElement)node; string unitTestName = unitTestElement.GetAttribute("Name"); if (selectedUnitTests.IsMatch(unitTestName)) { unitTestElement.SetAttribute("TempDirectory", this.tempFileCollection.BasePath); this.unitTestElements.Enqueue(node); } break; } } } if (this.unitTests.Count > 0) { this.totalUnitTests = this.unitTestElements.Count; int numThreads; if (this.updateTests || this.singleThreaded) { // If the tests are running with the -update switch, they must run on one thread // so that all execution is paused when the user is prompted to update a test. numThreads = 1; } else { // create a thread for each processor numThreads = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS"), CultureInfo.InvariantCulture); } Thread[] threads = new Thread[numThreads]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ThreadStart(this.RunUnitTests)); threads[i].Start(); } // wait for all threads to finish foreach (Thread thread in threads) { thread.Join(); } // report the results Console.WriteLine(); int elapsedTime = (Environment.TickCount - beginTickCount) / 1000; if (0 < this.failedUnitTests.Count) { Console.WriteLine("Summary of failed tests:"); Console.WriteLine(); // Put the failed tests into an ArrayList, which will get serialized ArrayList serializedFailedTests = new ArrayList(); foreach (string failedTest in this.failedUnitTests.Keys) { serializedFailedTests.Add(failedTest); Console.WriteLine("{0}. {1}", this.failedUnitTests[failedTest], failedTest); } Console.WriteLine(); Console.WriteLine("Re-run the failed tests with the -rf option"); Console.WriteLine(); Console.WriteLine("Failed {0} out of {1} unit test{2} ({3} seconds).", this.failedUnitTests.Count, this.totalUnitTests, (1 != this.completedUnitTests ? "s" : ""), elapsedTime); using (XmlWriter writer = XmlWriter.Create(this.failedTestsFile)) { XmlSerializer serializer = new XmlSerializer(serializedFailedTests.GetType()); serializer.Serialize(writer, serializedFailedTests); writer.Close(); } } else { Console.WriteLine("Successful unit tests: {0} ({1} seconds).", this.completedUnitTests, elapsedTime); } Console.WriteLine(); } else { Console.WriteLine("No unit tests were selected."); } } catch (WixException we) { this.messageHandler.Display(this, we.Error); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException) { throw; } } finally { if (this.noTidy) { Console.WriteLine(); Console.WriteLine("The notidy option was specified, temporary files can be found at:"); Console.WriteLine(this.tempFileCollection.BasePath); } else { // try three times and give up with a warning if the temp files aren't gone by then const int RetryLimit = 3; for (int i = 0; i < RetryLimit; i++) { try { Directory.Delete(this.tempFileCollection.BasePath, true); // toast the whole temp directory break; // no exception means we got success the first time } catch (UnauthorizedAccessException) { if (0 == i) // should only need to unmark readonly once - there's no point in doing it again and again { RecursiveFileAttributes(this.tempFileCollection.BasePath, FileAttributes.ReadOnly, false); // toasting will fail if any files are read-only. Try changing them to not be. } else { break; } } catch (DirectoryNotFoundException) { // if the path doesn't exist, then there is nothing for us to worry about break; } catch (IOException) // directory in use { if (i == (RetryLimit - 1)) // last try failed still, give up { break; } Thread.Sleep(300); // sleep a bit before trying again } } } } return(this.failedUnitTests.Count); }
/// <summary> /// Look at <see cref="IFormatter.Format"/> documentation. /// </summary> public virtual void Format(XmlSchemaCollection schemas, StringBuilder output) { }
private IDocumentPlug CreateEDIDocumentPlug(int currentTransactionSetType, string[] ISARecordFields) { string targetNamespace, name; IDocumentPlug documentPlug = null; switch (currentTransactionSetType) { case 820: name = "X12_005010X306_820R1"; targetNamespace = @"urn:x12:schemas:005010X306:820R1:HealthInsuranceExchangeRelatedPayments"; if (SchemaCache.ContainsKey(name)) { documentPlug = SchemaCache[name]; } break; case 850: name = "X12_00401_850"; targetNamespace = @"http://schemas.microsoft.com/BizTalk/EDI/X12/2006"; if (SchemaCache.ContainsKey(name)) { documentPlug = SchemaCache[name]; } break; case 277: name = "X12_005010X214_277B3"; //targetNamespace = @"urn:x12:schemas:005:010:277B3:HealthCareInformationStatusNotification"; targetNamespace = @"http://schemas.microsoft.com/BizTalk/EDI/X12/2006"; if (SchemaCache.ContainsKey(name)) { documentPlug = SchemaCache[name]; } break; case 810: name = "X12_00501_810"; targetNamespace = @"http://schemas.microsoft.com/BizTalk/EDI/X12/2006"; if (SchemaCache.ContainsKey(name)) { documentPlug = SchemaCache[name]; } break; default: throw new PlugDataModelException(string.Format("{0} schema not found", currentTransactionSetType)); } if (documentPlug == null) { string docType = string.Format("{0}#{1}", targetNamespace, name); Stream schemaStream = FPManager.RetrieveSchema(docType); XmlReader reader = new XmlTextReader(schemaStream); //Stream schemaStream = FatPipeManager.RetrieveSchema(rootNodeName); //XmlReader reader = new XmlTextReader(schemaStream); XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); schemaCollection.Add(targetNamespace, reader); documentPlug = DocumentPlugFactory.CreateDocumentPlugFromXmlSchema(schemaCollection, targetNamespace, name); SchemaCache[name] = documentPlug; } return(documentPlug); }
public void Add(XmlSchemaCollection schema) { }
/// <summary> /// Main entry point for sample application. /// </summary> /// <param name="args"></param> public static void Main(string[] args) { XmlSchema myXmlSchema; XmlTextWriter myXmlTextWriter; try { Console.WriteLine ("Creating Schema in the Schema Object Model..."); // Setup console output. myXmlTextWriter = new XmlTextWriter(Console.Out); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.Indentation = 2; //Create an XmlNameTable. XmlNameTable myXmlNameTable = new NameTable(); //Add the nametable to the XmlSchemaCollection. XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection(myXmlNameTable); //Add some schemas to the XmlSchemaCollection. Console.WriteLine ("Reading and adding {0} schema.", BOOKSCHEMA); myXmlSchemaCollection.Add(null, BOOKSCHEMA); Console.WriteLine ("Reading and adding {0} schema.", POSCHEMA); myXmlSchemaCollection.Add(null, POSCHEMA); Console.WriteLine ("Added schemas successfully ..."); Console.WriteLine ("Showing added schemas"); foreach(XmlSchema myTempXmlSchema in myXmlSchemaCollection) { myXmlSchema = myTempXmlSchema; Console.WriteLine(); string outfile = myTempXmlSchema.SourceUri.Replace("file:///", ""); Console.WriteLine("Schema from: {0}", outfile); Console.WriteLine(); Console.WriteLine("=== Start of Schema ==="); Console.WriteLine(); // Write out the various schema parts WriteXSDSchema(myXmlSchema, myXmlTextWriter); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("=== End of Schema ==="); Console.WriteLine(); Console.WriteLine("Example of possible XML contents for: {0}", outfile); Console.WriteLine(); Console.WriteLine("=== Start of Example ==="); // Write out an example of the XML for the schema WriteExample(myXmlSchema, myXmlTextWriter); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("=== End of Example ==="); } //foreach } //try catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } //catch } //Main()
public Kernel(XmlSchemaCollection schemas) { m_Schemas = schemas; }
/// <summary> /// Método responsável por validar os arquivos XML de acordo com a estrutura determinada pelos schemas (XSD) /// </summary> /// <param name="cRotaArqXML"> /// Rota e nome do arquivo XML que é para ser validado. Exemplo: /// c:\unimake\uninfe\envio\teste-nfe.xml /// </param> /// <param name="cRotaArqSchema"> /// Rota e nome do arquivo XSD que é para ser utilizado para validar o XML. Exemplo: /// c:\unimake\uninfe\schemas\nfe_v1.10.xsd /// </param> /// <example> /// ValidadorXMLClass oValidarXML = new ValidadorXMLClass; /// oValidarXML(@"c:\unimake\uninfe\teste-nfe.xml", @"c:\unimake\uninfe\schemas\nfe_v1.10.xsd") /// if (this.Retorno == 0) /// { /// MessageBox.Show("Validado com sucesso") /// } /// else /// { /// MessageBox.Show("Ocorreu erro na validação: \r\n\r\n" + this.RetornoString) /// } /// </example> /// <date>31/07/2008</date> /// <by>Wandrey Mundin Ferreira</by> public void Validar(string cRotaArqXML, string cRotaArqSchema) { bool lArqXML = File.Exists(cRotaArqXML); var caminhoDoSchema = this.PastaSchema + "\\" + cRotaArqSchema; bool lArqXSD = File.Exists(caminhoDoSchema); if (lArqXML && lArqXSD) { //TODO: V3.0 - Colocar Try Catch StreamReader cStreamReader = new StreamReader(cRotaArqXML); XmlTextReader cXmlTextReader = new XmlTextReader(cStreamReader); XmlValidatingReader reader = new XmlValidatingReader(cXmlTextReader); // Criar um coleção de schema, adicionar o XSD para ela XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); schemaCollection.Add(ConfiguracaoApp.nsURI, caminhoDoSchema); // Adicionar a coleção de schema para o XmlValidatingReader reader.Schemas.Add(schemaCollection); // Wire up the call back. The ValidationEvent is fired when the // XmlValidatingReader hits an issue validating a section of the xml reader.ValidationEventHandler += new ValidationEventHandler(reader_ValidationEventHandler); // Iterate through the xml document this.cErro = ""; try { while (reader.Read()) { } } catch (Exception ex) { this.cErro = ex.Message; } reader.Close(); this.Retorno = 0; this.RetornoString = ""; if (cErro != "") { this.Retorno = 1; this.RetornoString = "Início da validação...\r\n\r\n"; this.RetornoString += "Arquivo XML: " + cRotaArqXML + "\r\n"; this.RetornoString += "Arquivo SCHEMA: " + caminhoDoSchema + "\r\n\r\n"; this.RetornoString += this.cErro; this.RetornoString += "\r\n...Final da validação"; } } else { if (lArqXML == false) { this.Retorno = 2; this.RetornoString = "Arquivo XML não foi encontrato"; } else if (lArqXSD == false) { this.Retorno = 3; this.RetornoString = "Arquivo XSD (schema) não foi encontrado em " + caminhoDoSchema; } } }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { try { XmlSchemaCollection objectSchema = new XmlSchemaCollection(); FileInfo currentFile = null; ArrayList intermediates = new ArrayList(); Librarian librarian = null; // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.FoundError) { return(this.messageHandler.PostProcess()); } if (0 == this.objectFiles.Count) { this.showHelp = true; } else if (null == this.outputFile) { if (1 < this.objectFiles.Count) { throw new ArgumentException("must specify output file when using more than one input file", "-out"); } FileInfo fi = (FileInfo)this.objectFiles[0]; this.outputFile = new FileInfo(Path.ChangeExtension(fi.Name, ".wix")); // we'll let the linker change the extension later } if (this.showLogo) { Assembly litAssembly = Assembly.GetExecutingAssembly(); Console.WriteLine("Microsoft (R) Windows Installer Xml Library Tool version {0}", litAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved."); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: lit.exe [-?] [-nologo] [-out outputFile] objectFile [objectFile ...]"); Console.WriteLine(); Console.WriteLine(" -nologo skip printing lit logo information"); Console.WriteLine(" -out specify output file (default: write to current directory)"); Console.WriteLine(); Console.WriteLine(" -ext extension (class, assembly), should extend SchemaExtension or BinderExtension"); Console.WriteLine(" -ss suppress schema validation of documents (performance boost)"); Console.WriteLine(" -sv suppress intermediate file version mismatch checking"); Console.WriteLine(" -ust use small table definitions (for backwards compatiblity)"); Console.WriteLine(" -wx treat warnings as errors"); Console.WriteLine(" -w<N> set the warning level (0: show all, 3: show none)"); Console.WriteLine(" -sw suppress all warnings (same as -w3)"); Console.WriteLine(" -sw<N> suppress warning with specific message ID"); Console.WriteLine(" -v verbose output (same as -v2)"); Console.WriteLine(" -v<N> sets the level of verbose output (0: most output, 3: none)"); Console.WriteLine(" -? this help information"); Console.WriteLine(); Console.WriteLine("Common extensions:"); Console.WriteLine(" .wxs - Windows installer Xml Source file"); Console.WriteLine(" .wxi - Windows installer Xml Include file"); Console.WriteLine(" .wixobj - Windows installer Xml Object file (in XML format)"); Console.WriteLine(" .wixlib - Windows installer Xml Library file (in XML format)"); Console.WriteLine(" .wixout - Windows installer Xml Output file (in XML format)"); Console.WriteLine(); Console.WriteLine(" .msm - Windows installer Merge Module"); Console.WriteLine(" .msi - Windows installer Product Database"); Console.WriteLine(" .mst - Windows installer Transform"); Console.WriteLine(" .pcp - Windows installer Patch Creation Package"); Console.WriteLine(); Console.WriteLine("For more information see: http://wix.sourceforge.net"); return(this.messageHandler.PostProcess()); } // create the librarian librarian = new Librarian(this.useSmallTables); librarian.Message += new MessageEventHandler(this.messageHandler.Display); // load any extensions foreach (string extension in this.extensionList) { Type extensionType = Type.GetType(extension); if (null == extensionType) { throw new WixInvalidExtensionException(extension); } if (extensionType.IsSubclassOf(typeof(SchemaExtension))) { librarian.AddExtension((SchemaExtension)Activator.CreateInstance(extensionType)); } } // load the object schema if (!this.suppressSchema) { Assembly wixAssembly = Assembly.Load("wix"); using (Stream objectsSchemaStream = wixAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.objects.xsd")) { XmlReader reader = new XmlTextReader(objectsSchemaStream); objectSchema.Add("http://schemas.microsoft.com/wix/2003/04/objects", reader); } } // add the Intermediates to the librarian foreach (FileInfo objectFile in this.objectFiles) { currentFile = objectFile; // load the object file into an intermediate object and add it to the list to be linked using (Stream fileStream = new FileStream(currentFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { XmlReader fileReader = new XmlTextReader(fileStream); try { XmlReader intermediateReader = fileReader; if (!this.suppressSchema) { intermediateReader = new XmlValidatingReader(fileReader); ((XmlValidatingReader)intermediateReader).Schemas.Add(objectSchema); } Intermediate intermediate = Intermediate.Load(intermediateReader, currentFile.FullName, librarian.TableDefinitions, this.suppressVersionCheck); intermediates.Add(intermediate); continue; // next file } catch (WixNotIntermediateException) { // try another format } Library objLibrary = Library.Load(currentFile.FullName, librarian.TableDefinitions, this.suppressVersionCheck); intermediates.AddRange(objLibrary.Intermediates); } currentFile = null; } // and now for the fun part Library library = librarian.Combine((Intermediate[])intermediates.ToArray(typeof(Intermediate))); // save the library output if an error did not occur if (null != library) { library.Save(this.outputFile.FullName); } } catch (WixException we) { // TODO: once all WixExceptions are converted to errors, this clause // should be a no-op that just catches WixFatalErrorException's this.messageHandler.Display("lit.exe", "LIT", we); return(1); } catch (Exception e) { this.OnMessage(WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } return(this.messageHandler.PostProcess()); }
public MGParamParser(Stream xmlInput) { this.xmlInput = xmlInput; try { XmlNodeList temp; IEnumerator nodeEnum; // Make document out of stream // Begin by adding schema Assembly thisAssm = Assembly.GetExecutingAssembly(); Stream xmlInputSchema = thisAssm.GetManifestResourceStream("inputSchema"); XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection(); myXmlSchemaCollection.Add(null, new XmlTextReader(xmlInputSchema)); // Then validate file (validation fills in defaults) XmlTextReader myXmlTextReader = new XmlTextReader(xmlInput); XmlValidatingReader myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader); myXmlValidatingReader.Schemas.Add(myXmlSchemaCollection); myXmlValidatingReader.ValidationType = ValidationType.Schema; this.paramInput = new XmlDocument(); paramInput.Load(myXmlValidatingReader); // Extract nodes we care about temp = paramInput.GetElementsByTagName("assemblyIdentity"); if (temp.Count != 1) { throw new MGParseErrorException("XML parameters should only have 1 assemblyIdentity element"); } else { nodeEnum = temp.GetEnumerator(); nodeEnum.MoveNext(); assmIDNode = (XmlNode)nodeEnum.Current; } temp = paramInput.GetElementsByTagName("description"); if (temp.Count != 1) { throw new MGParseErrorException("XML parameters should only have 1 description element"); } else { nodeEnum = temp.GetEnumerator(); nodeEnum.MoveNext(); descNode = (XmlNode)nodeEnum.Current; } temp = paramInput.GetElementsByTagName("applicationParams"); if (temp.Count != 1) { throw new MGParseErrorException("XML parameters should only have 1 applicationParams element"); } else { nodeEnum = temp.GetEnumerator(); nodeEnum.MoveNext(); appNode = (XmlNode)nodeEnum.Current; } temp = paramInput.GetElementsByTagName("subscriptionParams"); if (temp.Count != 1) { throw new MGParseErrorException("XML parameters should only have 1 subscriptionParams element"); } else { nodeEnum = temp.GetEnumerator(); nodeEnum.MoveNext(); subNode = (XmlNode)nodeEnum.Current; } temp = paramInput.GetElementsByTagName("platformParams"); if (temp.Count > 1) { throw new MGParseErrorException("XML parameters should have at most 1 platformParams element"); } else if (temp.Count == 1) { nodeEnum = temp.GetEnumerator(); nodeEnum.MoveNext(); platNode = (XmlNode)nodeEnum.Current; } // Extract application name appName = assmIDNode.Attributes["name"].Value; // Set up specialized assembly ID nodes appAssmIDNode = assmIDNode.Clone(); subAssmIDNode = assmIDNode.Clone(); XmlAttribute typeAttr1 = paramInput.CreateAttribute("type"); XmlAttribute typeAttr2 = (XmlAttribute)typeAttr1.CloneNode(true); typeAttr1.Value = "application"; appAssmIDNode.Attributes.Prepend(typeAttr1); typeAttr2.Value = "subscription"; subAssmIDNode.Attributes.Prepend(typeAttr2); } catch (XmlException xmle) { throw new MGParseErrorException("XML parameter parsing failed", xmle); } catch (XmlSchemaException xmlse) { throw new MGParseErrorException("XML parameter validation failed", xmlse); } }
/// <summary> /// Gets an appropriate <see cref="System.Xml.XmlReader"/> implementation /// for the supplied <see cref="System.IO.Stream"/>. /// </summary> /// <param name="stream">The XML <see cref="System.IO.Stream"/> that is going to be read.</param> /// <param name="schemas">XML schemas that should be used for validation.</param> /// <param name="eventHandler">Validation event handler.</param> /// <returns> /// A validating <see cref="System.Xml.XmlReader"/> implementation. /// </returns> public static XmlReader CreateValidatingReader(Stream stream, XmlSchemaCollection schemas, ValidationEventHandler eventHandler) { return(CreateValidatingReader(stream, new XmlUrlResolver(), schemas, eventHandler)); }
public NSTScorePartwise ParseString(string dataString) { //todo: parse string IList <NSTPart> partList = new List <NSTPart>(); XmlTextReader textReader = new XmlTextReader(new FileStream("C:\\NM\\ScoreTranscription\\NETScoreTranscription\\NETScoreTranscriptionLibrary\\OtherDocs\\musicXML.xsd", System.IO.FileMode.Open)); //todo: pass stream in instead of absolute location for unit testing XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); schemaCollection.Add(null, textReader); NSTScorePartwise score; using (XmlValidatingReader reader = new XmlValidatingReader(XmlReader.Create(new StringReader(dataString), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse }))) //todo: make unobsolete { reader.Schemas.Add(schemaCollection); reader.ValidationType = ValidationType.Schema; reader.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationEventHandler); XmlSerializer serializer = new XmlSerializer(typeof(NSTScorePartwise), new XmlRootAttribute("score-partwise")); score = (NSTScorePartwise)serializer.Deserialize(reader); /* * while (reader.Read()) * { * if (reader.IsEmptyElement) * throw new Exception(reader.Value); //todo: test * * switch (reader.NodeType) * { * case XmlNodeType.Element: * switch (reader.Name.ToLower()) * { * case "part-list": * break; * case "score-partwise": * break; * case "part-name": * throw new Exception("pn"); * break; * } * break; * case XmlNodeType.Text: * * break; * case XmlNodeType.XmlDeclaration: * case XmlNodeType.ProcessingInstruction: * * break; * case XmlNodeType.Comment: * * break; * case XmlNodeType.EndElement: * * break; * } * }*/ } return(score); }
/// <summary> /// Main method for the MsgGen application within the MsgGenMain class. /// </summary> /// <param name="args">Commandline arguments to the application.</param> public MsgGenMain(string[] args) { this.showLogo = true; this.showHelp = false; this.sourceFile = null; this.destClassFile = null; this.destResourcesFile = null; // parse the command line this.ParseCommandLine(args); if (null == this.sourceFile || null == this.destClassFile) { this.showHelp = true; } if (null == this.destResourcesFile) { this.destResourcesFile = Path.ChangeExtension(this.destClassFile, ".resources"); } // get the assemblies Assembly msgGenAssembly = Assembly.GetExecutingAssembly(); if (this.showLogo) { Console.WriteLine("Microsoft (R) Message Generation Tool version {0}", msgGenAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2004. All rights reserved."); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: MsgGen.exe [-?] [-nologo] sourceFile destClassFile [destResourcesFile]"); Console.WriteLine(); Console.WriteLine(" -? this help information"); Console.WriteLine(); Console.WriteLine("For more information see: http://wix.sourceforge.net"); return; // exit } // load the schema XmlReader reader = null; XmlSchemaCollection schemaCollection = null; try { reader = new XmlTextReader(msgGenAssembly.GetManifestResourceStream("WixBuildTools.MsgGen.Xsd.messages.xsd")); schemaCollection = new XmlSchemaCollection(); schemaCollection.Add("http://schemas.microsoft.com/genmsgs/2004/07/messages", reader); } finally { reader.Close(); } // load the source file and process it using (StreamReader sr = new StreamReader(this.sourceFile)) { XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.None); XmlValidatingReader validatingReader = new XmlValidatingReader(sr.BaseStream, XmlNodeType.Document, context); validatingReader.Schemas.Add(schemaCollection); XmlDocument errorsDoc = new XmlDocument(); errorsDoc.Load(validatingReader); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); using (ResourceWriter resourceWriter = new ResourceWriter(this.destResourcesFile)) { GenerateMessageFiles.Generate(errorsDoc, codeCompileUnit, resourceWriter); GenerateCSharpCode(codeCompileUnit, this.destClassFile); } } }
/// <summary> /// ITestStep.Execute() implementation /// </summary> /// <param name='data'>The stream cintaining the data to be validated.</param> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public void ExecuteValidation(Stream data, Context context) { var doc = new XmlDocument(); var trData = new XmlTextReader(data); var xsc = new XmlSchemaCollection(); using (var vr = new XmlValidatingReader(trData)) { // If schema was specified use it to vaidate against... if (null != _xmlSchemaPath) { using (var xsdSchema = StreamHelper.LoadFileToStream(_xmlSchemaPath)) { using (var trSchema = new XmlTextReader(xsdSchema)) { if (null != _xmlSchemaNameSpace) { xsc.Add(_xmlSchemaNameSpace, trSchema); vr.Schemas.Add(xsc); } doc.Load(vr); } } } } data.Seek(0, SeekOrigin.Begin); doc.Load(data); foreach (var validation in XPathValidations) { var xpathExp = (string)validation.First; var expectedValue = (string)validation.Second; context.LogInfo("XmlValidationStepEx evaluting XPath {0} equals \"{1}\"", xpathExp, expectedValue); var xpn = doc.CreateNavigator(); var result = xpn.Evaluate(xpathExp); string checkValue = null; if (result.GetType().Name == "XPathSelectionIterator") { var xpi = result as XPathNodeIterator; xpi.MoveNext(); // BUGBUG! if (null != xpi) { checkValue = xpi.Current.ToString(); } } else { checkValue = result.ToString(); } if (0 != expectedValue.CompareTo(checkValue)) { throw new InvalidOperationException( string.Format("XmlValidationStepEx failed, compare {0} != {1}, xpath query used: {2}", expectedValue, checkValue, xpathExp)); } } }
#pragma warning disable 618 internal bool CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, string ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, bool CompileContentModel) { //Need to lock here to prevent multi-threading problems when same schema is added to set and compiled lock (this) { //Preprocessing SchemaCollectionPreprocessor prep = new SchemaCollectionPreprocessor(nameTable, null, validationEventHandler); prep.XmlResolver = resolver; if (!prep.Execute(this, ns, true, xsc)) { return false; } //Compilation SchemaCollectionCompiler compiler = new SchemaCollectionCompiler(nameTable, validationEventHandler); isCompiled = compiler.Execute(this, schemaInfo, CompileContentModel); this.SetIsCompiled(isCompiled); // return isCompiled; } }
/// <summary> /// Look at <see cref="IFormatter.Format"/> documentation. /// </summary> public override void Format(XmlSchemaCollection schemas, StringBuilder output) { output.Insert(0, "Results from XML Schema validation:\r\n"); output.Append("\r\n"); }