Implements a generic URL resolver for use with XML and XSL documents, and that any custom resolvers can be registered with.
Inheritance: System.Xml.XmlUrlResolver
Ejemplo n.º 1
0
        /// <inheritdoc/>
        public EntityResult GetEntity(UrlResolver parent, SageContext context, string uri)
        {
            var request = WebRequest.Create(uri);
            request.Timeout = timeout;

            if (!string.IsNullOrWhiteSpace(accept))
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, accept);

            if (!string.IsNullOrWhiteSpace(acceptLanguage))
                request.Headers.Add(HttpRequestHeader.AcceptLanguage, acceptLanguage);

            var result = new EntityResult();
            try
            {
                WebResponse response = request.GetResponse();
                result.Entity = new StreamReader(response.GetResponseStream());
            }
            catch (Exception ex)
            {
                XmlDocument document = new XmlDocument();
                document.InnerXml = string.Format("<error uri=\"{0}\">{1}</error>", uri, ex.Message);
                result.Entity = new XmlNodeReader(document);
            }

            return result;
        }
Ejemplo n.º 2
0
        /// <inheritdoc/>
        public EntityResult GetEntity(UrlResolver parent, SageContext context, string resourceUri)
        {
            string resourceName = this.GetResourceName(resourceUri);
                XmlReaderSettings settings = CacheableXmlDocument.CreateReaderSettings(parent);

            CacheableXmlDocument resourceDoc;

            // first check if we have a registered provider for the specified resour name
            if (providers.ContainsKey(resourceName))
            {
                XmlProvider provider = providers[resourceName];
                log.DebugFormat("Found a specific resource provider for {0}: {1}",
                    resourceUri,
                    Util.GetMethodSignature(provider.Method));

                resourceDoc = provider(context, resourceUri);
            }
            else
            {
                string sourcePath = context.Path.Expand(resourceName);
                if (sourcePath == null || !File.Exists(sourcePath))
                    throw new FileNotFoundException(string.Format("The specified resource '{0}' doesn't exist.", resourceUri));

                resourceDoc = context.Resources.LoadXml(sourcePath);
            }

            XmlReader reader = XmlReader.Create(new StringReader(resourceDoc.OuterXml), settings, resourceUri);
            return new EntityResult { Entity = reader, Dependencies = resourceDoc.Dependencies };
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Renders the result of the original view with an additional <see cref="XsltTransform"/>.
        /// </summary>
        /// <param name="viewContext">The view context.</param>
        /// <param name="writer">The writer to write to.</param>
        public override void Render(ViewContext viewContext, TextWriter writer)
        {
            Contract.Requires<ArgumentNullException>(viewContext != null);
            Contract.Requires<ArgumentException>(viewContext.Controller is SageController);
            Contract.Requires<ArgumentNullException>(writer != null);

            if (this.View is XsltView)
            {
                XsltView view = (XsltView) this.View;
                StringBuilder sb = new StringBuilder();

                using (StringWriter sw = new StringWriter(sb))
                {
                    view.Transform(viewContext, sw);

                    SageController controller = (SageController) viewContext.Controller;
                    UrlResolver resolver = new UrlResolver(controller.Context);
                    XmlReaderSettings settings = CacheableXmlDocument.CreateReaderSettings(resolver);
                    XmlReader reader = XmlReader.Create(new StringReader(sb.ToString()), settings);

                    XmlDocument viewXml = new XmlDocument();
                    viewXml.Load(reader);

                    processor.Transform(viewXml, writer, controller.Context);
                }

                this.DisableCaching(viewContext);
            }
            else
            {
                base.Render(viewContext, writer);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets an <see cref="EntityResult"/> that represents the actual resource mapped from the specified <paramref name="uri"/>.
        /// </summary>
        /// <param name="parent">The <see cref="UrlResolver"/> that owns this resolved and calls this method.</param>
        /// <param name="context">The current <see cref="SageContext"/> under which this code is executing.</param>
        /// <param name="uri">The uri to resolve.</param>
        /// <returns>
        /// An object that represents the resource mapped from the specified <paramref name="uri"/>.
        /// </returns>
        public EntityResult GetEntity(UrlResolver parent, SageContext context, string uri)
        {
            string sourcePath = uri.Replace(Scheme + "://", string.Empty);
            EntityResult result = null;
            Stopwatch sw = new Stopwatch();
            long time = sw.TimeMilliseconds(() => result = this.GetClientResourceReader(context, sourcePath));
            log.DebugFormat("Time taken to get resource reader for '{0}': {1}ms", uri, time);

            return result;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MsXsltTransform"/> class, using the specified 
        /// <paramref name="stylesheetMarkup"/>.
        /// </summary>
        /// <param name="context">The current context.</param>
        /// <param name="stylesheetMarkup">The markup to initialize the transform with.</param>
        public MsXsltTransform(SageContext context, XmlDocument stylesheetMarkup)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(stylesheetMarkup != null);

            UrlResolver resolver = new UrlResolver(context);

            processor = new XslCompiledTransform();

            try
            {
                processor.Load(stylesheetMarkup, XsltSettings.TrustedXslt, resolver);
                dependencies.AddRange(resolver.Dependencies);
            }
            catch (Exception ex)
            {
                ProblemInfo problem = this.DetectProblemType(ex);
                throw new SageHelpException(problem, ex);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SaxonXsltTransform"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stylesheetMarkup">The stylesheet markup.</param>
        /// <exception cref="SageHelpException"></exception>
        public SaxonXsltTransform(SageContext context, XmlDocument stylesheetMarkup)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(stylesheetMarkup != null);

            UrlResolver resolver = new UrlResolver(context);

            processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Build(stylesheetMarkup);
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(XmlReader.Create(stylesheetMarkup.OuterXml)).Load();

            try
            {
                //this.processor.Load(stylesheetMarkup, XsltSettings.TrustedXslt, resolver);
                dependencies.AddRange(resolver.Dependencies);
            }
            catch //(Exception ex)
            {
                //ProblemInfo problem = this.DetectProblemType(ex);
                //throw new SageHelpException(problem, ex);
            }
        }
Ejemplo n.º 7
0
        private void LoadInternal(string filename, SageContext context, bool processIncludes = true)
        {
            UrlResolver resolver = new UrlResolver(context);

            XmlReader xmlReader;
            XmlReaderSettings settings = CacheableXmlDocument.CreateReaderSettings(resolver);

            var resolvedUri = context == null ? filename : context.Path.Resolve(filename);
            Uri uri = new Uri(resolvedUri, UriKind.RelativeOrAbsolute);
            IDisposable reader = resolver.GetEntity(uri, null, null) as IDisposable;
            if (reader is XmlReader)
                xmlReader = (XmlReader) reader;
            else if (reader is Stream)
                xmlReader = XmlReader.Create((Stream) reader, settings, filename);
            else if (reader is TextReader)
                xmlReader = XmlReader.Create((TextReader) reader, settings, filename);
            else
                xmlReader = XmlReader.Create(filename, settings);

            this.AddDependencies(filename);
            using (xmlReader)
            {
                try
                {
                    base.Load(xmlReader);
                    this.AddDependencies(resolver.Dependencies);
                }
                finally
                {
                    if (xmlReader.ReadState != ReadState.Closed)
                        xmlReader.Close();
                }
            }

            baseUri = uri.ToString();

            if (processIncludes)
                this.ProcessIncludes(this.DocumentElement, context);
        }
Ejemplo n.º 8
0
        /// <inheritdoc/>
        public override void Transform(XmlNode inputXml, XmlWriter outputWriter, SageContext context, Dictionary<string, object> arguments = null)
        {
            var startTime = DateTime.Now.Ticks;

            XmlWriter xmlWriter = XmlWriter.Create(outputWriter, this.OutputSettings);
            XmlWriter output = new XHtmlXmlWriter(xmlWriter);
            XmlNodeReader reader = new XmlNodeReader(inputXml);

            UrlResolver resolver = new UrlResolver(context);
            XsltArgumentList transformArgs = this.GetArguments(arguments);

            try
            {
                processor.Transform(reader, transformArgs, output, resolver);
            }
            catch (Exception ex)
            {
                ProblemInfo problem = this.DetectProblemType(ex);
                throw new SageHelpException(problem, ex);
            }
            finally
            {
                reader.Close();
                output.Close();
                xmlWriter.Close();
            }

            var ellapsed = new TimeSpan(DateTime.Now.Ticks - startTime);
            log.DebugFormat("XSLT transform completed in {0}ms", ellapsed.Milliseconds);
        }
Ejemplo n.º 9
0
        private static CacheableXmlDocument LoadSourceDocument(string path, SageContext context)
        {
            UrlResolver resolver = new UrlResolver(context);
            CacheableXmlDocument result = new CacheableXmlDocument();
            result.Load(path, context);
            result.AddDependencies(path);
            result.AddDependencies(resolver.Dependencies.ToArray());

            return result;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Validates the specified document <paramref name="document"/> against the XML schema loaded from the specified
        /// <paramref name="schemaPath"/>, and returns an object that contains the validation information.
        /// </summary>
        /// <param name="document">The document to validate.</param>
        /// <param name="schemaPath">The path to the XML schema to use to validate the document against.</param>
        /// <returns>An object that contains the validation information</returns>
        public static ValidationResult ValidateDocument(XmlDocument document, string schemaPath)
        {
            Contract.Requires<ArgumentNullException>(document != null);
            Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(schemaPath));

            ValidationResult result = new ValidationResult();
            XmlSchemaSet schemaSet = null;
            if (!string.IsNullOrWhiteSpace(schemaPath))
            {
                UrlResolver resolver = new UrlResolver();
                XmlReaderSettings settings = CacheableXmlDocument.CreateReaderSettings(resolver);
                XmlReader reader = XmlReader.Create(schemaPath, settings);
                XmlSchema schema = XmlSchema.Read(reader, null);

                schemaSet = new XmlSchemaSet { XmlResolver = resolver };
                schemaSet.Add(schema);
                schemaSet.Compile();
            }

            XDocument xdocument = XDocument.Parse(document.OuterXml, LoadOptions.SetLineInfo);
            xdocument.Validate(schemaSet, (sender, args) =>
            {
                if (args.Severity == XmlSeverityType.Error)
                {
                    result.Success = false;

                    var lineInfo = sender as IXmlLineInfo;
                    if (lineInfo != null)
                    {
                        result.Exception = new XmlException(args.Message, args.Exception, lineInfo.LineNumber, lineInfo.LinePosition);
                    }
                    else
                    {
                        result.Exception = args.Exception;
                    }
                }
            });

            return result;
        }