Ejemplo n.º 1
0
        public override void TransformFileToFile(XMLUtilities.XSLParameter[] parameterList, string sInputPath, string sOutputName)
        {
            try
            {

                // Add any parameters
                AddParameters(parameterList);

                // apply transform
                var inputUri = new Uri(sInputPath);
                var sr = new StreamReader(sInputPath, Encoding.UTF8);
                XdmNode inputNode = m_processor.NewDocumentBuilder().Build(inputUri);
                sr.Close();
                m_transformer.InitialContextNode = inputNode;

                var ser = new Serializer();
                ser.SetOutputFile(sOutputName);

                m_transformer.Run(ser);
                ser.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.InnerException.ToString());
            }
        }
Ejemplo n.º 2
0
        public static void Main()
        {
            using (FileStream streamXml = File.OpenRead(XmlPath))
            {
                using (FileStream streamXsl = File.OpenRead(XsltPath))
                {
                    Processor processor = new Processor();

                    DocumentBuilder builder = processor.NewDocumentBuilder();
                    Uri uri = new Uri("urn:catalogue");
                    builder.BaseUri = uri;
                    XdmNode input = builder.Build(streamXml);
                    XsltTransformer transformer = processor.NewXsltCompiler().Compile(streamXsl).Load();
                    transformer.InitialContextNode = input;
                    Serializer serializer = new Serializer();
                    serializer.SetOutputFile(HtmlPath);
                    transformer.Run(serializer);
                }
            }

            Console.WriteLine("catalogue.html created successfully");
        }
 public XmlDestination HandleResultDocument(string href, Uri baseUri)
 {
     var dest = new Serializer();
     dest.SetOutputFile(Path.Combine(baseUri.LocalPath, href));
     return dest;
 }
Ejemplo n.º 4
0
    public void go(String[] args)
    {
        processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");
        testSuiteDir = args[0];
        if (testSuiteDir.EndsWith("/"))
        {
            testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1);
        }
        saxonResultsDir = args[1];
        if (saxonResultsDir.EndsWith("/"))
        {
            saxonResultsDir = saxonResultsDir.Substring(0, testSuiteDir.Length - 1);
        }
        Hashtable exceptions = new Hashtable();

        if (args.Length > 1)
        {
            testPattern = (args[2]); // TODO: allow a regex
        }

        for (int i = 0; i < args.Length; i++)
        {
            if (args[i].Equals("-w"))
            {
                //showWarnings = true;
            }

        }

        fileComparer = new FileComparer(processor, testSuiteDir);

        XPathCompiler xpc = processor.NewXPathCompiler();
        xpc.DeclareNamespace("t", testURI);
        xpc.DeclareVariable(new QName("", "param"));
        findSourcePath = xpc.Compile("//t:test-suite/t:sources/t:source[@ID=$param]");

        findCollection = xpc.Compile("//t:test-suite/t:sources/t:collection[@ID=$param]");

        xpc = processor.NewXPathCompiler();
        xpc.DeclareNamespace("t", testURI);
        xpc.DeclareVariable(new QName("", "testcase"));
        xpc.DeclareVariable(new QName("", "moduleuri"));
        findModule = xpc.Compile("for $m in $testcase/t:module[@namespace=$moduleuri] " +
            "return concat('file:///" + testSuiteDir +
            "/', root($testcase)/t:test-suite/t:sources/t:module[@ID=string($m)]/@FileName, '.xq')");

        //xpc = processor.NewXPathCompiler();
        //xpc.DeclareNamespace("saxon", "http://saxon.sf.net/");
        //xpc.DeclareVariable(new QName("", "actual"));
        //xpc.DeclareVariable(new QName("", "gold"));
        //xpc.DeclareVariable(new QName("", "debug"));
        //compareDocuments = xpc.Compile("saxon:deep-equal($actual, $gold, (), if ($debug) then 'JNCPS?!' else 'JNCPS')");

        QName testCaseNT = new QName(testURI, "test-case");
        QName nameNT = new QName(testURI, "name");
        QName queryNT = new QName(testURI, "query");
        QName inputNT = new QName(testURI, "input");
        QName inputFileNT = new QName(testURI, "input-file");
        QName inputUriNT = new QName(testURI, "input-URI");
        QName defaultCollectionNT = new QName(testURI, "defaultCollection");
        QName outputFileNT = new QName(testURI, "output-file");
        QName expectedErrorNT = new QName(testURI, "expected-error");
        QName schemaNT = new QName(testURI, "schema");
        QName contextItemNT = new QName(testURI, "contextItem");
        QName inputQueryNT = new QName(testURI, "input-query");
        QName sourceDocumentNT = new QName(testURI, "source-document");
        QName errorNT = new QName(testURI, "error");
        QName validationNT = new QName(testURI, "validation");
        QName discretionaryItemsNT = new QName(testURI, "discretionary-items");
        QName discretionaryFeatureNT = new QName(testURI, "discretionary-feature");
        QName discretionaryChoiceNT = new QName(testURI, "discretionary-choice");
        QName initialContextNodeNT = new QName(testURI, "initial-context-node");

        QName fileAtt = new QName("", "file");
        QName filePathAtt = new QName("", "FilePath");
        QName fileNameAtt = new QName("", "FileName");
        QName errorIdAtt = new QName("", "error-id");
        QName compareAtt = new QName("", "compare");
        QName nameAtt = new QName("", "name");
        QName behaviorAtt = new QName("", "behavior");
        QName qnameAtt = new QName("", "qname");
        QName modeAtt = new QName("", "mode");
        QName validatesAtt = new QName("", "validates");
        QName variableAtt = new QName("", "variable");
        QName roleAtt = new QName("", "role");

        DocumentBuilder builder = processor.NewDocumentBuilder();
        XdmNode exceptionsDoc = builder.Build(new Uri(saxonResultsDir + "/exceptions-n.xml"));

        // The exceptions.xml file contains details of tests that aren't to be run, for example
        // because they have known bugs or require special configuration

        IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName("", "exception"));
        while (exceptionTestCases.MoveNext())
        {
            XdmNode n = (XdmNode)exceptionTestCases.Current;
            String nameAttVal = n.StringValue;
            char[] seps = { ' ', '\n', '\t' };
            String[] parts = nameAttVal.Split(seps);
            foreach (string p in parts)
            {
                if (!exceptions.ContainsKey(p))
                {
                    exceptions.Add(p, "Exception");
                }
            }
        }

        // Hash table containing all source documents. The key is the document name in the
        // catalog, the value is the corresponding document node

        Hashtable sourceDocs = new Hashtable(50);

        // Load the catalog

        XdmNode catalog = builder.Build(new Uri(testSuiteDir + "/XQTScatalog.xml"));

        // Add all Static Typing test cases to the exceptions list

        xpc = processor.NewXPathCompiler();
        xpc.DeclareNamespace("t", testURI);
        XPathSelector st = xpc.Compile("//t:test-group[@name='StaticTyping']//t:test-case").Load();
        st.ContextItem = catalog;
        IEnumerator ste = st.GetEnumerator();
        while (ste.MoveNext())
        {
            XdmNode testCase = (XdmNode)ste.Current;
            exceptions.Add(testCase.GetAttributeValue(nameAtt), "StaticTypingException");
        }

        // Create the results file and log file

        results = new StreamWriter(saxonResultsDir + "/results"
                    + processor.ProductVersion + "n.xml");
        log = new StreamWriter(saxonResultsDir + "/log"
                    + processor.ProductVersion + "n.xml");

        log.WriteLine("Testing Saxon " + processor.ProductVersion);
        results.WriteLine("<test-suite-result xmlns='http://www.w3.org/2005/02/query-test-XQTSResult'>");

        // Pre-load all the schemas

        SchemaManager mgr = processor.SchemaManager;
        IEnumerator se = catalog.EnumerateAxis(XdmAxis.Descendant, schemaNT);
        while (se.MoveNext())
        {
            XdmNode schemaNode = (XdmNode)se.Current;
            log.WriteLine("Loading schema " + schemaNode.GetAttributeValue(fileNameAtt));
            Uri location = new Uri(testSuiteDir + "/" + schemaNode.GetAttributeValue(fileNameAtt));
            mgr.Compile(location);
        }

        total = 0;
        IEnumerator testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT);
        while (testCases.MoveNext()) {
            total++;
        }

        // Process the test cases in turn

        testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT);
        while (testCases.MoveNext())
        {
            XdmNode testCase = (XdmNode)testCases.Current;

            String testName = testCase.GetAttributeValue(nameAtt);
            if (testPattern != null && !testName.StartsWith(testPattern))
            {
                continue;
            }
            if (exceptions.ContainsKey(testName))
            {
                continue;
            }

            log.WriteLine("Test " + testName);

            // Compile the query

            String errorCode = null;

            String filePath = testCase.GetAttributeValue(filePathAtt);
            XdmNode query = getChildElement(testCase, queryNT);
            String queryName = query.GetAttributeValue(nameAtt);
            String queryPath = testSuiteDir + "/Queries/XQuery/" + filePath + queryName + ".xq";

            XQueryCompiler compiler = processor.NewXQueryCompiler();
            compiler.BaseUri = new Uri(queryPath).ToString();
            compiler.QueryResolver = new XqtsModuleResolver(testCase, findModule);
            compiler.SchemaAware = true;
                // Set all queries to schema-aware, because we don't really know whether they will have to handle typed input or not.

            ArrayList errors = new ArrayList();
            compiler.ErrorList = errors;
            XQueryEvaluator xqe = null;
            FileStream stream = null;
            try
            {
                stream = new FileStream(queryPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                xqe = compiler.Compile(stream).Load();
            }
            catch (Exception e)
            {
                if (errors.Count > 0 && ((StaticError)errors[0]).ErrorCode != null)
                {
                    errorCode = ((StaticError)errors[0]).ErrorCode.LocalName;
                }
                else if (e is StaticError && ((StaticError)e).ErrorCode != null)
                {
                    log.WriteLine(e.Message);
                    errorCode = ((StaticError)e).ErrorCode.LocalName;
                }
                else
                {
                    log.WriteLine(e.Message);
                    errorCode = "ErrorXXX";
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            // if the query compiled successfully, try to run it

            String outputPath = null;
            if (errorCode == null && xqe != null)
            {

                // Supply any input documents

                IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, inputFileNT);
                while (en.MoveNext())
                {
                    XdmNode file = (XdmNode)en.Current;
                    String var = file.GetAttributeValue(variableAtt);
                    if (var != null)
                    {
                        String sourceName = file.StringValue;
                        XdmNode sourceDoc;
                        if (sourceDocs.ContainsKey(sourceName))
                        {
                            sourceDoc = (XdmNode)sourceDocs[sourceName];
                        }
                        else
                        {
                            sourceDoc = buildSource(catalog, builder, sourceName);
                            sourceDocs.Add(sourceName, sourceDoc);
                        }
                        xqe.SetExternalVariable(new QName("", var), sourceDoc);
                    }
                }

                // Supply any input URIs

                IEnumerator eu = testCase.EnumerateAxis(XdmAxis.Child, inputUriNT);
                while (eu.MoveNext())
                {
                    XdmNode file = (XdmNode)eu.Current;
                    String var = file.GetAttributeValue(variableAtt);
                    if (var != null)
                    {
                        String sourceName = file.StringValue;
                        if (sourceName.StartsWith("collection"))
                        {
                            // Supply a collection URI.
                            // This seems to be the only way to distinguish a document URI
                            // from a collection URI.
                            String uri = "collection:" + sourceName;
                            XPathSelector xpe = findCollection.Load();
                            xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName));
                            xpe.ContextItem = catalog;
                            XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle();
                            if (collectionNode == null)
                            {
                                log.WriteLine("*** Collection " + sourceName + " not found");
                            }
                            processor.RegisterCollection(new Uri(uri), getCollection(collectionNode));
                            xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri));
                        }
                        else
                        {
                            // Supply a document URI.
                            // We exploit the fact that the short name of the document is
                            // always the same as the file name in these tests. With one exception!
                            if (sourceName == "Char010D")
                            {
                                sourceName = "0x010D";
                            }
                            String uri = "file:///" + testSuiteDir + "/TestSources/" + sourceName + ".xml";
                            xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri));
                        }
                    }
                }

                // Supply the default collection if required

                XdmNode defaultCollection = getChildElement(testCase, defaultCollectionNT);
                if (defaultCollection != null)
                {
                    String sourceName = defaultCollection.StringValue;
                    XPathSelector xpe = findCollection.Load();
                    xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName));
                    xpe.ContextItem = catalog;
                    XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle();
                    if (collectionNode == null)
                    {
                        log.WriteLine("*** Collection " + sourceName + " not found");
                    }
                    processor.RegisterCollection(null, getCollection(collectionNode));
                }

                // Supply any external variables defined as the result of a separate query

                IEnumerator ev = testCase.EnumerateAxis(XdmAxis.Child, inputQueryNT);
                while (ev.MoveNext())
                {
                    XdmNode inputQuery = (XdmNode)ev.Current;

                    String fileName = inputQuery.GetAttributeValue(nameAtt);
                    String subQueryPath = testSuiteDir + "/Queries/XQuery/" + filePath + fileName + ".xq";
                    XQueryCompiler subCompiler = processor.NewXQueryCompiler();
                    compiler.BaseUri = new Uri(subQueryPath).ToString();
                    FileStream subStream = new FileStream(subQueryPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    XdmValue value = subCompiler.Compile(subStream).Load().Evaluate();
                    String var = inputQuery.GetAttributeValue(variableAtt);
                    xqe.SetExternalVariable(new QName("", var), value);
                }

                // Supply the context item if required

                IEnumerator ci = testCase.EnumerateAxis(XdmAxis.Child, contextItemNT);
                while (ci.MoveNext())
                {
                    XdmNode file = (XdmNode)ci.Current;

                    String sourceName = file.StringValue;
                    if (!sourceDocs.ContainsKey(sourceName))
                    {
                        XdmNode doc = buildSource(catalog, builder, sourceName);
                        sourceDocs.Add(sourceName, doc);
                    }
                    XdmNode sourceDoc = (XdmNode)sourceDocs[sourceName];
                    xqe.ContextItem = sourceDoc;
                }

                // Create a serializer for the output

                outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out";
                Serializer sr = new Serializer();
                try
                {
                    sr.SetOutputFile(outputPath);
                    sr.SetOutputProperty(new QName("", "method"), "xml");
                    sr.SetOutputProperty(new QName("", "omit-xml-declaration"), "yes");
                    sr.SetOutputProperty(new QName("", "indent"), "no");
                }
                catch (DynamicError)
                {
                    // probably means that no output directory exists, which is probably because
                    // an error is expected
                    outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out";
                    sr.SetOutputFile(outputPath);
                }

                // Finally, run the query

                try
                {
                    xqe.Run(sr);
                }
                catch (DynamicError e)
                {
                    log.WriteLine(e.Message);
                    QName code = e.ErrorCode;
                    if (code != null && code.LocalName != null)
                    {
                        errorCode = code.LocalName;
                    }
                    else
                    {
                        errorCode = "ErrYYYYY";
                    }
                }
                catch (Exception e2)
                {
                    log.WriteLine("Unexpected exception: " + e2.Message);
                    log.WriteLine(e2.StackTrace);
                    errorCode = "CRASH!!!";
                }
            }

            // Compare actual results with expected results

            if (errorCode != null)
            {
                // query returned an error at compile time or run-time, check this was expected

                string expectedError = "";
                bool matched = false;
                IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT);
                while (en.MoveNext())
                {
                    XdmNode error = (XdmNode)en.Current;
                    String expectedErrorCode = error.StringValue;
                    expectedError += (expectedErrorCode + " ");
                    if (expectedErrorCode.Equals(errorCode))
                    {
                        matched = true;
                        feedback.Feedback(passed++, failed, total);
                        log.WriteLine("Error " + errorCode + " as expected");
                        results.WriteLine("<test-case name='" + testName + "' result='pass'/>");
                        break;
                    }
                }
                if (!matched)
                {
                    if (expectedError.Equals(""))
                    {
                        feedback.Feedback(passed, failed++, total);
                        log.WriteLine("Error " + errorCode + ", expected success");
                        results.WriteLine("<test-case name='" + testName + "' result='fail' comment='error " + errorCode + ", expected success'/>");
                        results.WriteLine("<--" + filePath + queryName + "-->");
                    }
                    else
                    {
                        feedback.Feedback(passed++, failed, total);
                        log.WriteLine("Error " + errorCode + ", expected " + expectedError);
                        results.WriteLine("<test-case name='" + testName + "' result='pass' comment='error " + errorCode + ", expected " + expectedError + "'/>");
                        results.WriteLine("<--" + filePath + queryName + "-->");
                    }
                }

            }
            else
            {
                // query returned no error

                bool matched = false;
                String diag = "";
                IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, outputFileNT);
                while (en.MoveNext())
                {
                    XdmNode outputFile = (XdmNode)en.Current;
                    String fileName = testSuiteDir + "/ExpectedTestResults/" + filePath + outputFile.StringValue;
                    String comparator = outputFile.GetAttributeValue(compareAtt);
                    if (comparator.Equals("Inspect"))
                    {
                        matched = true;
                        feedback.Feedback(passed++, failed, total);
                        results.WriteLine("<test-case name='" + testName + "' result='inspect'/>");
                        results.WriteLine("<--" + filePath + queryName + "-->");
                        break;
                    }
                    else
                    {
                        String comparison = fileComparer.compare(outputPath, fileName, comparator);
                        matched = (comparison == "OK" || comparison.StartsWith("#"));
                        if (matched)
                        {
                            feedback.Feedback(passed++, failed, total);
                            results.WriteLine("<test-case name='" + testName + "' result='pass'/>");
                            diag = diag + ("<!-- " + comparison + " -->\n");
                            break;
                        }
                    }
                }

                if (!matched)
                {
                    string expectedError = "";
                    IEnumerator ee = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT);
                    while (ee.MoveNext())
                    {
                        XdmNode error = (XdmNode)ee.Current;
                        String expectedErrorCode = error.StringValue;
                        expectedError += (expectedErrorCode + " ");
                    }

                    if (expectedError.Equals(""))
                    {
                        feedback.Feedback(passed, failed++, total);
                        log.WriteLine("Results differ from expected results");
                        results.WriteLine("<test-case name='" + testName + "' result='fail'/>");
                        results.WriteLine("<--" + filePath + queryName + "-->");
                    }
                    else
                    {
                        feedback.Feedback(passed, failed++, total);
                        log.WriteLine("Error " + expectedError + "expected but not reported");
                        results.WriteLine("<test-case name='" + testName + "' result='fail' comment='expected error " + expectedError + "not reported'/>");
                        results.WriteLine("<--" + filePath + queryName + "-->");
                    }
                }
            }
        }

        results.WriteLine("</test-suite-result>");
        results.Close();
        log.Close();
    }
Ejemplo n.º 5
0
    /**
     * Runs an XSLT transform, serializing the result to a new temporary file.
     *
     * @param name="src" the document to be transformed
     * @param name="stylesheet" the stylesheet to use
     */
    public static void transform(String src, String stylesheet, String tempFile )
    {
        XsltExecutable compiled = compileStylesheet(stylesheet);
        XsltTransformer transformer = compiled.Load();

        XdmNode doc = getSourceRoot(src);
        if (doc == null)
        {
            Console.WriteLine("error: null transform source root node");
            Environment.Exit(-1);
        }

        transformer.InitialContextNode = doc;
        Serializer serializer = new Serializer();
        serializer.SetOutputFile(tempFile);
        transformer.Run(serializer);
        serializer.Close();
    }
Ejemplo n.º 6
0
    /// <summary>
    /// Run the transformation
    /// </summary>
    /// <param name="testName"></param>
    /// <param name="xml"></param>
    /// <param name="xsl"></param>
    /// <param name="initialMode"></param>
    /// <param name="initialTemplate"></param>
    /// <param name="outfile"></param>
    /// <param name="paramTable"></param>
    /// <param name="initialContextPath"></param>
    /// <param name="useAssociated"></param>
    /// <param name="schemaAware"></param>
    /// <param name="validationMode"></param>
    /// <param name="recoverRecoverable"></param>
    /// <returns>Either null, indicating success, or an Exception object with information about the failure</returns>

    protected Exception runXSLT(String testName, String xml, String xsl, QName initialMode,
                           QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath,
                           bool useAssociated, bool schemaAware,
                           String validationMode, bool recoverRecoverable, bool useXSLT30)
    {
        Serializer sr = new Serializer();
        sr.SetOutputFile(outfile);
        Processor f;
        if (noCacheTests.ContainsKey(testName)) {
            //create a custom Processor to avoid schema caching
            f = new Processor(true);
        }
        else if (schemaAware)
        {
            f = schemaAwareProcessor;
            if (f == null)
            {
                return new DynamicError("Saxon-SA not available");
            }
        }
        else if (xml11)
        {
            f = processor;
            // Use an Xml 1.1 processor
        }
        else
        {
            f = processor;
        }
        

        XdmNode source = null;

        IList errors = new ArrayList();
        XsltCompiler compiler = f.NewXsltCompiler();
        compiler.SchemaAware = schemaAware;
        compiler.ErrorList = errors;
        if (useXSLT30)
        {
            compiler.XsltLanguageVersion = "3.0";
        }
        XsltExecutable sheet = null;
        XsltTransformer inst;

        if (useAssociated)
        {
            try
            {
                source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to build source document: " + e.Message);
                return e;
            }
            try
            {
                sheet = compiler.CompileAssociatedStylesheet(source);
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to compile stylesheet: " + e.Message);
                if (errors.Count > 0)
                {
                    return (Exception)errors[0];
                    //QName code = ((StaticError)errors[0]).ErrorCode;
                    //(code == null ? "Failed to compile stylesheet: " + e.Message : code.LocalName);
                }
                else
                {
                    return e;
                }
            }
        }
        else
        {
            Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read);
            compiler.BaseUri = new Uri(xsl);
            try
            {
                sheet = compiler.Compile(stream);
            }
            catch (StaticError e)
            {
                if (errors.Count > 0)
                {
                    return ((StaticError)errors[0]);
                }
                else
                {
                    log.WriteLine(e.Message);
                    return e;
                }
            }
            catch (Exception e2)
            {
                log.WriteLine("Unexpected CRASH: " + e2.Message);
                log.WriteLine(e2.StackTrace);
                return e2;
            }
            finally
            {
                stream.Close();
            }
        }
        if (initialContextPath != null)
        {
            if (source == null && xml != null)
            {
                try
                {
                    source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
                }
                catch (Exception e)
                {
                    log.WriteLine("Failed to build source document: " + e.Message);
                    return e;
                }
            }

            XPathCompiler xc = f.NewXPathCompiler();
            XPathExecutable exp = xc.Compile(initialContextPath);
            XPathSelector xpe = exp.Load();
            xpe.ContextItem = source;
            XdmNode node = (XdmNode)xpe.EvaluateSingle();
            source = node;

        }

        inst = sheet.Load();
        if (source != null) {
            inst.InitialContextNode = source;
        }

        if (source == null && xml != null)
        {
            Stream stream = new FileStream(xml, FileMode.Open, FileAccess.Read);
            inst.SetInputStream(stream, new Uri(xml));
        }

        
        if (initialMode != null)
        {
            inst.InitialMode = initialMode;
        }
        if (initialTemplate != null)
        {
            try
            {
                inst.InitialTemplate = initialTemplate;
            }
            catch (DynamicError e)
            {
                return e;
            }
        }
        if (paramTable != null)
        {
            foreach (DictionaryEntry de in paramTable)
            {
                inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString()));
            }
        }
        
        inst.BaseOutputUri = new Uri(outfile);
        inst.RecoveryPolicy = recoverRecoverable ? RecoveryPolicy.RecoverSilently : RecoveryPolicy.DoNotRecover;

        if ("strict" == validationMode)
        {
            inst.SchemaValidationMode = SchemaValidationMode.Strict;
        }
        else
        {
            inst.SchemaValidationMode = SchemaValidationMode.None;
        }

        //inst.setURIResolver(factory.getURIResolver());
        //inst.setErrorListener(errorListener);
        //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER);
        // To avoid test results being dependent on the date and time (and timezone), set a fixed
        // date and time for the run
        //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00"));

        try
        {
            inst.Run(sr);
        }
        catch (DynamicError e)
        {
            log.WriteLine(e.Message);
            return e;
        }
        catch (Exception e2)
        {
            log.WriteLine("Unexpected CRASH: " + e2.Message);
            log.WriteLine(e2.StackTrace);
            return e2;
        }
        return null;    // indicating success
    }
Ejemplo n.º 7
0
        /// <summary>
        /// выполнить конвертацию тем
        /// </summary>
        public void Do()
        {
            try
            {
                if (themes == null || themes.Count<XElement>() < 1)
                    return;

                //XslCompiledTransform xslt = new XslCompiledTransform();
                //xslt.Load(convParams.ThemeShemePath);

                foreach (XElement th in themes)
                {
                    SendMessage("- Конвертация темы "+th.Element(NodeNames.TITLE).Value);

                    XDocument doc = new XDocument(th);
                    string fn = th.Element(NodeNames.ITEM_FILE_ID).Value;
                    string themeFilesNewPath = Path.Combine(convParams.OutMediaFiles.AsPath(), fn).AsPath();
                    string outFile = Path.Combine(convParams.OutItemsPath, fn + ".html");
                    ///SAXON
                    Processor proc = new Processor();
                    XdmNode input = proc.NewDocumentBuilder().Build(doc.Root.CreateReader());

                    XsltTransformer transformer = proc.NewXsltCompiler().Compile(new Uri(convParams.ThemeShemePath)).Load();
                    transformer.InitialContextNode = input;

                    transformer.SetParameter(new QName("", "", "mediaPath"), new XdmAtomicValue(convParams.CourseDataFolderName));
                    transformer.SetParameter(new QName("", "", "picFolder"), new XdmAtomicValue(th.Element(NodeNames.ITEM_FILE_ID).Value));
                    transformer.SetParameter(new QName("", "", "toolFolder"), new XdmAtomicValue(convParams.ToolsDataFolderName));

                    ///задать адрес директории для xsl:result-document
                    transformer.BaseOutputUri = new Uri(themeFilesNewPath);
                    Serializer serializer = new Serializer();

                    serializer.SetOutputFile(outFile);

                    transformer.Run(serializer);

                    //doc.Document.Declaration = new XDeclaration("1.0", "utf-8", "true");
                    //XPathNavigator nv = doc.CreateNavigator();

                    //XsltArgumentList xslArg = new XsltArgumentList();

                    //xslArg.AddParam("mediaPath", "", convParams.CourseDataFolderName);
                    //xslArg.AddParam("picFolder", "", th.Element(NodeNames.ITEM_FILE_ID).Value);
                    //xslArg.AddParam("toolFolder", "", convParams.ToolsDataFolderName);

                    //string outFile = Path.Combine(convParams.OutItemsPath, th.Element(NodeNames.ITEM_FILE_ID).Value + ".html");
                    //using (FileStream fs = new FileStream(outFile, FileMode.Create))
                    //{
                    //    xslt.Transform(nv, xslArg, fs);
                    //}

                    Guid idTheme = Guid.Parse(th.Element(NodeNames.IDENTIFER).Value);
                    ItemThemeForXSLT theme = GetTheme(idTheme);
                    CopyThemeFiles(theme);
                    DoOtherOperation(theme);
                }
            }
            catch(Exception ex)
            {
                throw new Exception("Исключение при конвертации темы курса: "+ex.Message);
            }
        }
Ejemplo n.º 8
0
        void createHtmlFromXsl()
        {
            string resultDoc = projSettings.DestinationPath+projSettings.DocHtmlFileName;
            if(projSettings.StyleName == "OrteliusXml") resultDoc = projSettings.DestinationPath+"/orteliusXml.xml";
            string xmlDoc = projSettings.DestinationPath+projSettings.DocXmlFileName;
            string xslDoc = Path.GetDirectoryName(Application.ExecutablePath)+"/styles/"+projSettings.StyleName+".xsl";

            try{
                Processor processor = new Processor();
                System.IO.StreamReader reader = new System.IO.StreamReader(xmlDoc, System.Text.Encoding.UTF8);
                System.IO.TextWriter stringWriter = new System.IO.StringWriter();

                stringWriter.Write(reader.ReadToEnd());
                stringWriter.Close();

                reader.Close();

                System.IO.TextReader stringReader = new System.IO.StringReader(stringWriter.ToString());
                System.Xml.XmlTextReader reader2 = new System.Xml.XmlTextReader(stringReader);
                reader2.XmlResolver = null;

                // Load the source document
                XdmNode input = processor.NewDocumentBuilder().Build(reader2);

                // Create a transformer for the stylesheet.
                XsltTransformer transformer = processor.NewXsltCompiler().Compile(new System.Uri(xslDoc)).Load();
                transformer.InputXmlResolver = null;

                // Set the root node of the source document to be the initial context node
                transformer.InitialContextNode = input;

                // Create a serializer
                Serializer serializer = new Serializer();

                serializer.SetOutputFile(resultDoc);

                // Transform the source XML to System.out.
                transformer.Run(serializer);
            }
            catch(Exception e){

                //MessageBox.Show(e.ToString());
                systemSvar += "Error in xslt rendering:\r\n"+e.ToString();
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// выполнить конвертацию тем
        /// </summary>
        public void Do()
        {
            try
            {
                SendMessage("\n- Конвертация тестов");

                XslCompiledTransform xslt = new XslCompiledTransform();
                xslt.Load(convParams.TestShemePath);

                foreach (XElement tt in tests)
                {
                    usedIdentifers = new List<string>();

                    Guid idTest = Guid.Parse(tt.Element(NodeNames.IDENTIFER).Value);

                    ItemTestForXSLT test = (ItemTestForXSLT)itemsAdapter.GetCourseItem(idTest);
                    if (test == null)
                        throw new Exception("Не найден тест с идентификатором: " + idTest);

                    XDocument testDoc = XDocument.Load(test.XMLFilePath);
                    if (testDoc == null)
                        throw new Exception("Не удается загрузить тест " + idTest + ": " + test.XMLFilePath);

                    CorrectTest(testDoc);

                    string outFile = Path.Combine(convParams.OutItemsPath, test.FileName + ".html");

                    string testFilesNewPath = Path.Combine(convParams.OutMediaFiles.AsPath(), test.FileName).AsPath();

                    DirectoryHelper.CreateDirectory(testFilesNewPath, false);

                    ///SAXON
                    Processor proc = new Processor();
                    XdmNode input = proc.NewDocumentBuilder().Build(testDoc.Root.CreateReader());

                    XsltTransformer transformer = proc.NewXsltCompiler().Compile(new Uri(convParams.TestShemePath)).Load();
                    transformer.InitialContextNode = input;

                    transformer.SetParameter(new QName("", "", "mediaFolderName"), new XdmAtomicValue(convParams.CourseDataFolderName));
                    transformer.SetParameter(new QName("", "", "currentFolderName"), new XdmAtomicValue(test.FileName));

                    ///задать адрес директории для xsl:result-document
                    transformer.BaseOutputUri = new Uri(testFilesNewPath);
                    Serializer serializer = new Serializer();

                    serializer.SetOutputFile(outFile);

                    transformer.Run(serializer);

                    CopyTestFiles(test, testFilesNewPath);

                }
            }
            catch(Exception ex)
            {
                throw new Exception("Исключение при конвертации теста курса: "+ex.Message);
            }
        }