XsltViewer.cs
上传用户:hbhltzc
上传日期:2022-06-04
资源大小:1925k
文件大小:13k
源码类别:

xml/soap/webservice

开发平台:

Visual C++

  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Drawing;
  6. using System.Drawing.Drawing2D;
  7. using System.Data;
  8. using System.IO;
  9. using System.Text;
  10. using System.Windows.Forms;
  11. using System.Xml;
  12. using System.Xml.Xsl;
  13. using System.Net;
  14. namespace XmlNotepad {
  15.     public partial class XsltViewer : UserControl {
  16.         Uri baseUri;
  17.         XslCompiledTransform defaultss;
  18.         XslCompiledTransform xslt;
  19.         Uri xsltUri;
  20.         DateTime loaded;
  21.         XsltSettings settings;
  22.         XmlUrlResolver resolver;
  23.         ISite site;
  24.         XmlCache model;
  25.         XmlDocument doc;
  26.         bool showFileStrip = true;
  27.         string defaultSSResource = "XmlNotepad.DefaultSS.xslt";
  28.         IDictionary<Uri, bool> trusted = new Dictionary<Uri, bool>();
  29.         int stripHeight;
  30.         string html;
  31.         public XsltViewer() {
  32.             this.SetStyle(ControlStyles.ResizeRedraw, true);
  33.             this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
  34.             this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
  35.             InitializeComponent();
  36.             stripHeight = this.WebBrowser1.Top;
  37.             xslt = new XslCompiledTransform();
  38.             settings = new XsltSettings(true, false);
  39.             resolver = new XmlUrlResolver();
  40.             toolTip1.SetToolTip(this.BrowseButton, SR.BrowseButtonTooltip);
  41.             toolTip1.SetToolTip(this.SourceFileName, SR.XslFileNameTooltip);
  42.             toolTip1.SetToolTip(this.TransformButton, SR.TransformButtonTooltip);
  43.             BrowseButton.Click += new EventHandler(BrowseButton_Click);
  44.             this.SourceFileName.KeyDown += new KeyEventHandler(OnSourceFileNameKeyDown);
  45.             this.WebBrowser1.ScriptErrorsSuppressed = true;
  46.             this.WebBrowser1.WebBrowserShortcutsEnabled = true;            
  47.         }
  48.         public string DefaultStylesheetResource {
  49.             get { return this.defaultSSResource; }
  50.             set { this.defaultSSResource = value; }
  51.         }
  52.         public bool ShowFileStrip {
  53.             get { return this.showFileStrip; }
  54.             set {
  55.                 if (value != this.showFileStrip) {
  56.                     this.showFileStrip = value;
  57.                     if (value) {
  58.                         AnchorStyles saved = this.WebBrowser1.Anchor;
  59.                         this.WebBrowser1.Anchor = AnchorStyles.None;
  60.                         this.WebBrowser1.Location = new Point(0, stripHeight);
  61.                         this.WebBrowser1.Height = this.Height - stripHeight;
  62.                         this.WebBrowser1.Anchor = saved;
  63.                         this.panel1.Controls.Remove(this.tableLayoutPanel1);
  64.                         this.panel1.Controls.SetChildIndex(this.tableLayoutPanel1, 0);
  65.                     } else {
  66.                         AnchorStyles saved = this.WebBrowser1.Anchor;
  67.                         this.WebBrowser1.Location = new Point(0, 0);
  68.                         this.WebBrowser1.Height = this.Height;
  69.                         this.WebBrowser1.Anchor = saved;
  70.                         this.panel1.Controls.Add(this.tableLayoutPanel1);
  71.                     }
  72.                     this.TransformButton.Visible = value;
  73.                     this.BrowseButton.Visible = value;
  74.                     this.SourceFileName.Visible = value;
  75.                 }
  76.             }
  77.         }
  78.         void OnSourceFileNameKeyDown(object sender, KeyEventArgs e) {
  79.             if (e.KeyCode == Keys.Enter) {
  80.                 this.DisplayXsltResults();
  81.             }
  82.         }
  83.         XslCompiledTransform GetDefaultStylesheet() {
  84.             if (defaultss != null) {
  85.                 return defaultss;
  86.             }
  87.             using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(this.defaultSSResource)) {
  88.                 if (null != stream) {
  89.                     using (XmlReader reader = XmlReader.Create(stream)) {
  90.                         XslCompiledTransform t = new XslCompiledTransform();
  91.                         t.Load(reader);
  92.                         defaultss = t;
  93.                     }
  94.                 }
  95.             }
  96.             return defaultss;
  97.         }
  98.         protected override void OnPaint(PaintEventArgs e) {
  99.             if (this.showFileStrip && this.WebBrowser1.Top > 0 && this.Width > 0) {
  100.                 Graphics g = e.Graphics;
  101.                 Rectangle r = new Rectangle(0, 0, this.Width, this.WebBrowser1.Top);
  102.                 Color c1 = Color.FromArgb(250, 249, 245);
  103.                 Color c2 = Color.FromArgb(192, 192, 168);
  104.                 Color s1 = SystemColors.ControlLight;
  105.                 using (LinearGradientBrush brush = new LinearGradientBrush(r, c1, c2, LinearGradientMode.Vertical)) {
  106.                     g.FillRectangle(brush, r);
  107.                 }
  108.             }
  109.         }
  110.         public void SetSite(ISite site) {
  111.             this.site = site;
  112.             IServiceProvider sp = (IServiceProvider)site;
  113.             this.resolver = new XmlProxyResolver(sp);
  114.             this.model = (XmlCache)site.GetService(typeof(XmlCache));
  115.             this.model.ModelChanged += new EventHandler<ModelChangedEventArgs>(OnModelChanged);
  116.         }
  117.         void OnModelChanged(object sender, ModelChangedEventArgs e) {
  118.             OnModelChanged();
  119.         }
  120.         void OnModelChanged() {
  121.             this.doc = model.Document;
  122.             try {
  123.                 if (!string.IsNullOrEmpty(model.FileName)) {
  124.                     this.baseUri = new Uri(model.FileName);
  125.                 }
  126.                 this.SourceFileName.Text = model.XsltFileName;
  127.             } catch (Exception) {
  128.             }
  129.         }
  130.         Uri GetBaseUri() {
  131.             if (this.baseUri == null) {
  132.                 OnModelChanged();
  133.                 if (this.baseUri == null) {
  134.                     this.baseUri = new Uri(Application.StartupPath + "/");
  135.                 }
  136.             }
  137.             return this.baseUri;
  138.         }
  139.         protected override void OnLayout(LayoutEventArgs e) {
  140.             base.OnLayout(e);
  141.             if (showFileStrip) {
  142.                 this.WebBrowser1.Top = this.tableLayoutPanel1.Bottom;
  143.                 this.WebBrowser1.Height = this.Height - this.tableLayoutPanel1.Height;
  144.             } else {
  145.                 this.WebBrowser1.Top = 0;
  146.                 this.WebBrowser1.Height = this.Height;
  147.             }
  148.         }
  149.         public void DisplayXsltResults() {
  150.             DisplayXsltResults(doc);
  151.         }
  152.         public void DisplayXsltResults(XmlDocument context) {
  153.             Uri resolved = null;
  154.             try {
  155.                 XslCompiledTransform transform;
  156.                 string path = null;
  157.                 if (this.showFileStrip) {
  158.                     path = this.SourceFileName.Text.Trim();
  159.                 }
  160.                 if (string.IsNullOrEmpty(path)) {
  161.                     transform = GetDefaultStylesheet();
  162.                 } else {
  163.                     resolved = new Uri(baseUri, path);
  164.                     if (resolved != this.xsltUri || IsModified()) {
  165.                         this.loaded = DateTime.Now;
  166.                         settings.EnableScript = (trusted.ContainsKey(resolved));
  167.                         XmlReaderSettings rs = new XmlReaderSettings();
  168.                         rs.ProhibitDtd = false;
  169.                         rs.XmlResolver = resolver;
  170.                         using (XmlReader r = XmlReader.Create(resolved.AbsoluteUri, rs)) {
  171.                             xslt.Load(r, settings, resolver);
  172.                         }
  173.                     }
  174.                     transform = xslt;
  175.                 }
  176.                 if (null != transform) {
  177.                     StringWriter writer = new StringWriter();
  178.                     XmlReaderSettings settings = new XmlReaderSettings();
  179.                     settings.XmlResolver = new XmlProxyResolver(this.site);
  180.                     settings.ProhibitDtd = false;
  181.                     transform.Transform(XmlIncludeReader.CreateIncludeReader(context, settings, GetBaseUri().AbsoluteUri), null, writer);
  182.                     this.xsltUri = resolved;                       
  183.                     Display(writer.ToString());
  184.                 }
  185.             } catch (System.Xml.Xsl.XsltException x) {
  186.                 if (x.Message.Contains("XsltSettings")) {
  187.                     if (!trusted.ContainsKey(resolved) &&
  188.                         MessageBox.Show(this, SR.XslScriptCodePrompt, SR.XslScriptCodeCaption,
  189.                         MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) {
  190.                         trusted[resolved] = true;
  191.                         DisplayXsltResults();
  192.                         return;
  193.                     }
  194.                 }
  195.                 WriteError(x);
  196.             } catch (Exception x) {
  197.                 WriteError(x);
  198.             }
  199.         }
  200.         bool IsModified() {
  201.             if (this.xsltUri.IsFile) {
  202.                 string path = this.xsltUri.LocalPath;
  203.                 DateTime lastWrite = File.GetLastWriteTime(path);
  204.                 return this.loaded < lastWrite;
  205.             }
  206.             return false;
  207.         }
  208.         private void WriteError(Exception e) {
  209.             StringWriter writer = new StringWriter();
  210.             writer.WriteLine("<html><body><h3>");
  211.             writer.WriteLine(SR.TransformErrorCaption);
  212.             writer.WriteLine("</h3></body></html>");
  213.             while (e != null) {
  214.                 writer.WriteLine(e.Message);
  215.                 e = e.InnerException;
  216.             }
  217.             Display(writer.ToString());
  218.         }
  219.         private void Display(string content) {
  220.             if (content != this.html) {
  221.                 this.WebBrowser1.DocumentText = content;
  222.                 this.html = content;
  223.             }
  224.         }
  225.         private void BrowseButton_Click(object sender, EventArgs e) {
  226.             OpenFileDialog ofd = new OpenFileDialog();
  227.             ofd.Filter = SR.XSLFileFilter;
  228.             if (ofd.ShowDialog(this) == DialogResult.OK) {
  229.                 this.SourceFileName.Text = ofd.FileName;
  230.             }
  231.         }
  232.         private void TransformButton_Click(object sender, EventArgs e) {
  233.             this.DisplayXsltResults();
  234.         }
  235.         private Guid cmdGuid = new Guid("ED016940-BD5B-11CF-BA4E-00C04FD70816");
  236.         private enum OLECMDEXECOPT {
  237.             OLECMDEXECOPT_DODEFAULT         = 0,
  238.             OLECMDEXECOPT_PROMPTUSER        = 1,
  239.             OLECMDEXECOPT_DONTPROMPTUSER    = 2,
  240.             OLECMDEXECOPT_SHOWHELP          = 3
  241.         }
  242.         private enum MiscCommandTarget {
  243.             Find = 1,
  244.             ViewSource,
  245.             Options
  246.         }
  247.         private mshtml.HTMLDocument GetDocument() {
  248.             try {
  249.                 mshtml.HTMLDocument htm = (mshtml.HTMLDocument)this.WebBrowser1.Document.DomDocument;
  250.                 return htm;
  251.             } catch {
  252.                 throw (new Exception("Cannot retrieve the document from the WebBrowser control"));
  253.             }
  254.         }
  255.         public void ViewSource() {
  256.             IOleCommandTarget cmdt;
  257.             Object o = new object();
  258.             try {
  259.                 cmdt = (IOleCommandTarget)GetDocument();
  260.                 cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.ViewSource,
  261.                 (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o);
  262.             } catch (Exception e) {
  263.                 System.Windows.Forms.MessageBox.Show(e.Message);
  264.             }
  265.         }
  266.         public void Find() {
  267.             IOleCommandTarget cmdt;
  268.             Object o = new object();
  269.             try {
  270.                 cmdt = (IOleCommandTarget)GetDocument();
  271.                 cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.Find,
  272.                 (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o);
  273.             } catch (Exception e) {
  274.                 System.Windows.Forms.MessageBox.Show(e.Message);
  275.             }
  276.         }
  277.     }
  278.     [CLSCompliant(false), StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  279.     public struct OLECMDTEXT {
  280.         public uint cmdtextf;
  281.         public uint cwActual;
  282.         public uint cwBuf;
  283.         [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
  284.         public char rgwz;
  285.     }
  286.     [CLSCompliant(false), StructLayout(LayoutKind.Sequential)]
  287.     public struct OLECMD {
  288.         public uint cmdID;
  289.         public uint cmdf;
  290.     }
  291.     // Interop definition for IOleCommandTarget. 
  292.     [CLSCompliant(false), ComImport, Guid("b722bccb-4e68-101b-a2bc-00aa00404770"),
  293.     InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  294.     public interface IOleCommandTarget {
  295.         //IMPORTANT: The order of the methods is critical here. You
  296.         //perform early binding in most cases, so the order of the methods
  297.         //here MUST match the order of their vtable layout (which is determined
  298.         //by their layout in IDL). The interop calls key off the vtable ordering,
  299.         //not the symbolic names. Therefore, if you switched these method declarations
  300.         //and tried to call the Exec method on an IOleCommandTarget interface from your
  301.         //application, it would translate into a call to the QueryStatus method instead.
  302.         void QueryStatus(ref Guid pguidCmdGroup, UInt32 cCmds,
  303.             [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] OLECMD[] prgCmds, ref OLECMDTEXT CmdText);
  304.         void Exec(ref Guid pguidCmdGroup, uint nCmdId, uint nCmdExecOpt, ref object pvaIn, ref object pvaOut);
  305.     }
  306. }