CreateDocumentType() public method

public CreateDocumentType ( string name, string publicId, string systemId, string internalSubset ) : XmlDocumentType
name string
publicId string
systemId string
internalSubset string
return XmlDocumentType
示例#1
0
        internal static void Write(Stream stream, Dictionary<string, object> plist)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = null;

            XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(xmlDecl);
            XmlDocumentType xmlDocType = xmlDoc.CreateDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);
            xmlDoc.AppendChild(xmlDocType);

            XmlElement rootElement = xmlDoc.CreateElement("plist");
            rootElement.SetAttribute("Version", "1.0");
            xmlDoc.AppendChild(rootElement);

            xmlDoc.DocumentElement.SetAttribute("Version", "1.0");

            rootElement.AppendChild(CreateNode(xmlDoc, plist));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.Encoding = Encoding.UTF8;

            using (XmlWriter xw = XmlTextWriter.Create(stream, settings))
            {
                xmlDoc.Save(xw);
            }
        }
示例#2
0
 public void Render()
 {
     var xmlDocument = new XmlDocument();
     xmlDocument.AppendChild(xmlDocument.CreateDocumentType("html", null, null, null));
     htmlTag.RenderOn(xmlDocument);
     xmlDocument.Save(XmlWriter.Create(textWriter, new XmlWriterSettings { OmitXmlDeclaration = true }));
 }
        // Provides methods for structuring xml to produce an Svg (nested in an HTML doc).
        public SvgXmlBuilder()
        {
            HtmlDoc = new XmlDocument ();

            // HTML-level
            HtmlDoc.AppendChild (HtmlDoc.CreateDocumentType ("html", "", "", ""));
            htmlDocElement = HtmlDoc.CreateElement ("html");

            // Body-level
            bodyElement = HtmlDoc.CreateElement ("body");
            htmlDocElement.AppendChild (bodyElement);

            // svg document
            SvgElement = HtmlDoc.CreateElement ("svg");
            bodyElement.AppendChild (SvgElement);
            var svgName = HtmlDoc.CreateAttribute ("name");
            svgName.Value = "Geographical Region Statistic Map";
            SvgElement.Attributes.Append (svgName);

            // Attributes independent of data.
            var heightAttr = HtmlDoc.CreateAttribute ("height");
            heightAttr.Value = "100%";
            var widthAttr = HtmlDoc.CreateAttribute ("width");
            widthAttr.Value = "100%";
            SvgElement.Attributes.Append (heightAttr);
            SvgElement.Attributes.Append (widthAttr);

            // TODO: Use css/jquery-style formatting?
            //new Style
            var svgColorAttr = HtmlDoc.CreateAttribute ("style");
            svgColorAttr.Value = "background:black";
            SvgElement.Attributes.Append (svgColorAttr);
        }
 /// <summary>
 /// Validates the given xml document, throwing an exception if there
 /// is a validation failure
 /// </summary>
 /// <param name="xmlDocument">The xml document in a continuous 
 /// string</param>
 /// <param name="rootElementName">The root element name</param>
 /// <param name="dtd">The dtd path</param>
 /// <exception cref="InvalidXmlDefinitionException">Thrown if there
 /// is a validation failure</exception>
 public void ValidateDocument(string xmlDocument, string rootElementName, string dtd)
 {
     _xmlDocument = new XmlDocument();
     _xmlDocument.LoadXml(xmlDocument);
     _xmlDocument.InsertBefore(_xmlDocument.CreateDocumentType(rootElementName, null, null, dtd),
                                 _xmlDocument.DocumentElement);
     ValidateCurrentDocument();
 }
示例#5
0
    public static XmlElement CreateHtmlArticle(string title)
    {
      title += " – SimpleDLNA";

      var document = new XmlDocument();
      document.AppendChild(document.CreateDocumentType(
        "html", null, null, null));

      document.AppendChild(document.EL("html"));

      var head = document.EL("head");
      document.DocumentElement.AppendChild(head);
      head.AppendChild(document.EL("title", text: title));
      head.AppendChild(document.EL(
        "link",
        new AttributeCollection() {
          { "rel", "stylesheet" },
          { "type", "text/css" },
          { "href", "/static/browse.css" }
        }
        ));

      var body = document.EL("body");
      document.DocumentElement.AppendChild(body);

      var article = document.EL("article");
      body.AppendChild(article);

      var header = document.EL("header");
      header.AppendChild(document.EL("h1", text: title));
      article.AppendChild(header);

      var footer = document.EL("footer");
      footer.AppendChild(document.EL(
        "img",
        new AttributeCollection() { { "src", "/icon/smallPNG" } }
        ));
      footer.AppendChild(document.EL("h3", text: string.Format(
        "SimpleDLNA Media Server: sdlna/{0}.{1}",
        Assembly.GetExecutingAssembly().GetName().Version.Major,
        Assembly.GetExecutingAssembly().GetName().Version.Minor
        )));
      footer.AppendChild(document.EL(
        "p",
        new AttributeCollection() { { "class", "desc" } },
        "A simple, zero-config DLNA media server, that you can just fire up and be done with it."
        ));
      footer.AppendChild(document.EL("a",
        new AttributeCollection() {
          { "href", "https://github.com/nmaier/simpleDLNA/" }
        },
        "Fork me on GitHub"
        ));
      body.AppendChild(footer);

      return article;
    }
		public static XmlDocument XslExportTransform (XmlDocument doc)
		{
			XmlReader reader = Registry.GladeExportXsl.Transform (doc, null, (XmlResolver)null);
			doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			doc.Load (reader);

			XmlDocumentType doctype = doc.CreateDocumentType ("glade-interface", null, Glade20SystemId, null);
			doc.PrependChild (doctype);

			return doc;
		}
示例#7
0
        public static XmlNode CreatePlist(XmlDocument doc)
        {
            XmlDeclaration xmldecl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(xmldecl);
            XmlDocumentType docType = doc.CreateDocumentType("plist", "-//Apple Computer//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);
            doc.AppendChild(docType);

            XmlNode xml_plist = XMLOpt.CreateNode(doc, doc, "plist", null);
            XmlAttribute plistVersion = doc.CreateAttribute("version");
            plistVersion.Value = "1.0";
            xml_plist.Attributes.Append(plistVersion);
            return xml_plist;
        }
        public XmlDocument CreateDocument()
        {
            // <?xeditnet-profile ../xenwebprofile/bin/debug/xenwebprofile.dll!XenWebProfile.ProfileImpl?>

            XmlDocument doc=new XmlDocument();
            XmlDocumentType doctype=doc.CreateDocumentType(profileInfo.Root, profileInfo.PublicId, profileInfo.SystemId, null);
            XmlElement root=doc.CreateElement(profileInfo.Root);
            XmlProcessingInstruction pi=doc.CreateProcessingInstruction("xeditnet-profile", profileInfo.Profile);

            doc.AppendChild(doctype);
            doc.AppendChild(pi);
            doc.AppendChild(root);
            return doc;
        }
示例#9
0
		public static XmlDocument XslExportTransform (XmlDocument doc)
		{
			StringWriter sw = new StringWriter ();
			XmlWriter xw = XmlWriter.Create (sw);
			Registry.GladeExportXsl.Transform (doc, xw);
			XmlReader reader = XmlReader.Create (sw.ToString ());
			doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			doc.Load (reader);

			XmlDocumentType doctype = doc.CreateDocumentType ("glade-interface", null, Glade20SystemId, null);
			doc.PrependChild (doctype);

			return doc;
		}
示例#10
0
        private XmlDocumentType LoadDocumentTypeNode()
        {
            Debug.Assert(reader.NodeType == XmlNodeType.DocumentType);

            String publicId       = null;
            String systemId       = null;
            String internalSubset = reader.Value;
            String localName      = reader.LocalName;

            while (reader.MoveToNextAttribute())
            {
                switch (reader.Name)
                {
                case "PUBLIC":
                    publicId = reader.Value;
                    break;

                case "SYSTEM":
                    systemId = reader.Value;
                    break;
                }
            }

            XmlDocumentType     dtNode = doc.CreateDocumentType(localName, publicId, systemId, internalSubset);
            XmlValidatingReader vr     = reader as XmlValidatingReader;

            if (vr != null)
            {
                LoadDocumentType(vr, dtNode);
            }
            else
            {
                //construct our own XmlValidatingReader to parse the DocumentType node so we could get Entities and notations information
                XmlTextReader tr = reader as XmlTextReader;
                if (tr != null)
                {
                    dtNode.ParseWithNamespaces = tr.Namespaces;
                    ParseDocumentType(dtNode, true, tr.GetResolver());
                }
                else
                {
                    ParseDocumentType(dtNode);
                }
            }
            return(dtNode);
        }
示例#11
0
 public static dom4cs NewDocument(String vRootTag, String vEncoding, String vDTDFileName) {
   dom4cs newDOM4CS = new dom4cs();
   XmlDocument doc = new XmlDocument();
   if (vEncoding != null)
     newDOM4CS.FEncoding = vEncoding;
   XmlDeclaration xd = doc.CreateXmlDeclaration("1.0", newDOM4CS.FEncoding, null);
   doc.AppendChild(xd);
   if (vDTDFileName != null) {
     XmlDocumentType xdt = doc.CreateDocumentType(vRootTag, null, vDTDFileName, null);
     doc.AppendChild(xdt);
   }
   if (vRootTag != null) {
     XmlElement rn = doc.CreateElement(vRootTag);
     doc.AppendChild(rn);
   }
   newDOM4CS.XmlDoc = doc;
   return newDOM4CS;
 }
示例#12
0
 private void InitConfigXml()
 {
     ConfigXml = new XmlDocument();
     XmlDeclaration decl = ConfigXml.CreateXmlDeclaration("1.0", "GBK", "yes");
     ConfigXml.AppendChild(decl);
     XmlDocumentType doctype = ConfigXml.CreateDocumentType("root", null, null, "<!ELEMENT Station ANY><!ATTLIST Station SSN ID #REQUIRED>");
     ConfigXml.AppendChild(doctype);
     RootNode = ConfigXml.CreateElement("MapConfig");
     ConfigXml.AppendChild(RootNode);
     XmlNode node = ConfigXml.CreateElement("Map");
     RootNode.AppendChild(node);
     node = ConfigXml.CreateElement("Divs");
     RootNode.AppendChild(node);
     node = ConfigXml.CreateElement("Statics");
     RootNode.AppendChild(node);
     node = ConfigXml.CreateElement("Stations");
     RootNode.AppendChild(node);
     node = ConfigXml.CreateElement("Words");
     RootNode.AppendChild(node);
 }
        public static XmlDocument WriteRepository(ICurricularUnitFormRepository<CurricularUnitForm> cufr)
        {
            XmlDocument xmlFile = new XmlDocument();
            XmlDeclaration decl = xmlFile.CreateXmlDeclaration("1.0", "utf-8", null);
            xmlFile.InsertBefore(decl, xmlFile.DocumentElement);

            XmlDocumentType type = xmlFile.CreateDocumentType("fuc-repository", "template.dtd", null, null);
            xmlFile.AppendChild(type);
            XmlElement fuc_repo = xmlFile.CreateElement("fuc-repository");
            fuc_repo.SetAttribute("school", "Instituto Superior de Engenharia de Lisboa");
            fuc_repo.SetAttribute("language", "pt");
            xmlFile.AppendChild(fuc_repo);

            foreach (CurricularUnitForm cuf in cufr.GetAll())
            {
                /*http://stackoverflow.com/questions/982597/what-is-the-fastest-way-to-combine-two-xml-files-into-one*/
                var xmlTmp = xmlFile.ImportNode(Write(cuf, false).DocumentElement, true);
                fuc_repo.AppendChild(xmlTmp);
            }
            return xmlFile;
        }
示例#14
0
        private XmlDocumentType LoadDocumentTypeNode()
        {
            Debug.Assert(_reader.NodeType == XmlNodeType.DocumentType);

            String publicId       = null;
            String systemId       = null;
            String internalSubset = _reader.Value;
            String localName      = _reader.LocalName;

            while (_reader.MoveToNextAttribute())
            {
                switch (_reader.Name)
                {
                case "PUBLIC":
                    publicId = _reader.Value;
                    break;

                case "SYSTEM":
                    systemId = _reader.Value;
                    break;
                }
            }

            XmlDocumentType dtNode = _doc.CreateDocumentType(localName, publicId, systemId, internalSubset);

            IDtdInfo dtdInfo = _reader.DtdInfo;

            if (dtdInfo != null)
            {
                LoadDocumentType(dtdInfo, dtNode);
            }
            else
            {
                //construct our own XmlValidatingReader to parse the DocumentType node so we could get Entities and notations information
                ParseDocumentType(dtNode);
            }

            return(dtNode);
        }
        public static byte[] DataWithPropertyList(Dictionary<string, object> plist)
        {
            XmlDocument doc = new XmlDocument();
            doc.XmlResolver = new PlistDTDResolver();

            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
            doc.AppendChild(doc.CreateDocumentType("plist",
                                                            "-//Apple Computer/DTD PLIST 1.0//EN",
                                                            "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null));

            XmlElement root = doc.CreateElement("plist");
            root.SetAttribute("version", "1.0");

            ArrayList plistNodes = plist.PropertyListRepresentationWithKey(doc, null);
            foreach (XmlElement el in plistNodes) {
                root.AppendChild(el);
            }

            doc.AppendChild(root);

            MemoryStream stream = new MemoryStream();
            doc.Save(stream);
            return stream.ToArray();
        }
示例#16
0
        static void ExportX3D()
        {
            ClearConsole();

            try
            {
                // grab the selected objects
                Transform[] trs = Selection.GetTransforms(SelectionMode.TopLevel);

                // get a path to save the file
                string file = EditorUtility.SaveFilePanel("Save X3D file as", "${HOME}/Desktop", "", "x3d");
                outputPath = Path.GetDirectoryName(file);

                if(file.Length == 0)
                {
                    // TODO output error
                    return;
                }

                xml = new XmlDocument();

                defNamesInUse = new List<string>();

                XmlNode xmlHeader = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
                xml.AppendChild(xmlHeader);

                XmlDocumentType docType = xml.CreateDocumentType("X3D", "http://www.web3d.org/specifications/x3d-3.3.dtd", null, null);
                xml.AppendChild(docType);

                X3DNode = CreateNode("X3D");
                xml.AppendChild(X3DNode);

                sceneNode = CreateNode("Scene");
                X3DNode.AppendChild(sceneNode);

                ExportRenderSettings();

                XmlNode lhToRh = CreateNode("Transform");
                AddXmlAttribute(lhToRh, "scale", "1 1 -1");
                sceneNode.AppendChild(lhToRh);

                sceneNode = lhToRh;

                currentNodeIndex = 0;
                numNodesToExport = 0;

                // Count number of nodes for progress bar
                foreach(Transform tr in trs)
                    numNodesToExport += CountNodes(tr);

                foreach(Transform tr in trs)
                    sceneNode.AppendChild(TransformToX3D(tr));

                xml.Save(file);
            }
            catch(System.Exception e)
            {
                Debug.LogError(e.ToString());
            }

            EditorUtility.ClearProgressBar();
        }
示例#17
0
        /// <summary>
        /// Creates a new instance the XML grammar represented by this instance
        /// using the indicated element name as the root element for the document.
        /// </summary>
        /// <param name="rootElement">The name of the root element.</param>
        /// <returns>A new <see cref="XmlDocument"/> instance.</returns>
        public override XmlDocument NewInstance(string rootElement)
        {
            XmlDocument		document = new XmlDocument ();

            document.XmlResolver = XmlUtility.DefaultCatalog;

            document.AppendChild (document.CreateDocumentType (rootElement, publicId, systemId, null));
            document.AppendChild (document.CreateElement (rootElement));

            return (document);
        }
示例#18
0
        /// <inheritdoc />
        public override void Apply(XmlDocument document, string key)
        {
            // Set the evaluation context
            context["key"] = key;

            XPathExpression xpath = pathExpression.Clone();
            xpath.SetContext(context);

            // Evaluate the path
            string path = document.CreateNavigator().Evaluate(xpath).ToString();

            if(basePath != null)
                path = Path.Combine(basePath, path);

            string targetDirectory = Path.GetDirectoryName(path);

            if(!Directory.Exists(targetDirectory))
                Directory.CreateDirectory(targetDirectory);

            if(writeXhtmlNamespace)
            {
                document.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/1999/xhtml");
                document.LoadXml(document.OuterXml);
            }

            if (settings.OutputMethod == XmlOutputMethod.Html)
            {
                XmlDocumentType documentType = document.CreateDocumentType("html", null, null, null);
                if (document.DocumentType != null)
                {
                    document.ReplaceChild(documentType, document.DocumentType);
                }
                else
                {
                    document.InsertBefore(documentType, document.FirstChild);
                }
            }

            // Save the document.

            // selectExpression determines which nodes get saved. If there is no selectExpression we simply
            // save the root node as before. If there is a selectExpression, we evaluate the XPath expression
            // and save the resulting node set. The select expression also enables the "literal-text" processing
            // instruction, which outputs its content as unescaped text.
            if(selectExpression == null)
            {
                try
                {
                    using(XmlWriter writer = XmlWriter.Create(path, settings))
                    {
                        document.Save(writer);
                    }
                }
                catch(IOException e)
                {
                    base.WriteMessage(key, MessageLevel.Error, "An access error occurred while attempting to " +
                        "save to the file '{0}'. The error message is: {1}", path, e.GetExceptionMessage());
                }
                catch(XmlException e)
                {
                    base.WriteMessage(key, MessageLevel.Error, "Invalid XML was written to the output " +
                        "file '{0}'. The error message is: '{1}'", path, e.GetExceptionMessage());
                }
            }
            else
            {
                // IMPLEMENTATION NOTE: The separate StreamWriter is used to maintain XML indenting.  Without it
                // the XmlWriter won't honor our indent settings after plain text nodes have been written.
                using(StreamWriter output = File.CreateText(path))
                {
                    using(XmlWriter writer = XmlWriter.Create(output, settings))
                    {
                        XPathExpression select_xpath = selectExpression.Clone();
                        select_xpath.SetContext(context);

                        XPathNodeIterator ni = document.CreateNavigator().Select(selectExpression);

                        while(ni.MoveNext())
                        {
                            if(ni.Current.NodeType == XPathNodeType.ProcessingInstruction &&
                              ni.Current.Name.Equals("literal-text"))
                            {
                                writer.Flush();
                                output.Write(ni.Current.Value);
                            }
                            else
                                ni.Current.WriteSubtree(writer);
                        }
                    }
                }
            }

            // Raise an event to indicate that a file was created
            this.OnComponentEvent(new FileCreatedEventArgs(path, true));
        }
        public XmlDocument SVGMap(int cityID)
        {
            Database database = new Database();
            XmlDocument xmldoc = new XmlDocument();

            #region Doctype
            //  TODO: Não está a inserir o doctype correctamente
            XmlDocumentType doctype = xmldoc.CreateDocumentType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", "");
            xmldoc.AppendChild(doctype);
            #endregion

            #region Elemento Raiz
            XmlElement root = xmldoc.CreateElement("svg");
            root.SetAttribute("width", "100%");
            root.SetAttribute("height", "100%");
            root.SetAttribute("version", "1.1");
            root.SetAttribute("xmlns", "http://www.w3.org/2000/svg");
            #endregion
            
            database.connect();
                SVGCartography c = database.Query.SVGMap(cityID);
            database.disconnect();

            #region Criação do Mapa em SVG
            XmlElement g;
            g = xmldoc.CreateElement("g");
            g.SetAttribute("transform", "scale(5) translate(60,38) rotate(-90)");

            XmlElement line;

            foreach (SVGRoadSegment s in c.segments)
            {
                line = xmldoc.CreateElement("line");
                line.SetAttribute("x1", s.begin.x.ToString());
                line.SetAttribute("y1", s.begin.z.ToString());

                line.SetAttribute("x2", s.end.x.ToString());
                line.SetAttribute("y2", s.end.z.ToString());

                line.SetAttribute("style", "stroke:rgb(99,99,99);stroke-width:1");

                g.AppendChild(line);
            }

            XmlElement circle;

            foreach (PointOfInterest p in c.pointsOfInterest)
            {
                circle = xmldoc.CreateElement("circle");

                //  TODO: Aqui também deves fazer o translate
                circle.SetAttribute("cx", p.position.x.ToString());
                circle.SetAttribute("cy", p.position.z.ToString());
                circle.SetAttribute("r", "1");
                circle.SetAttribute("stroke", "black");
                circle.SetAttribute("stroke-width", "0.2");
                circle.SetAttribute("fill", "red");

                g.AppendChild(circle);
            }

            root.AppendChild(g);
            xmldoc.AppendChild(root);
            #endregion

            return xmldoc;
        }
示例#20
0
 /// <summary>
 /// Create a <see cref="XmlDocumentType"/> with the specified Id
 /// </summary>
 /// <param name="document"></param>
 /// <param name="name"></param>
 /// <param name="publicId"></param>
 /// <param name="systemId"></param>
 /// <returns></returns>
 static public XmlDocumentType CreateDocumentType(this XmlDocument document, string name, string publicId, string systemId)
 {
     return(document.CreateDocumentType(name, publicId, systemId, null));
 }
示例#21
0
        /// <summary>
        /// Save a dictionary into an XML file by passing the dictionary object and filename
        /// </summary>
        /// <param name="dictionary">The Dictionary.</param>
        /// <param name="filename">The full path of the file to write.</param>
        public static void DictionaryToFile(Dictionary<string, string> dictionary, string filename)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.XmlResolver = null;

            XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            xmlDocument.AppendChild(xmlDeclaration);

            xmlDocument.AppendChild(xmlDocument.CreateDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null));
            // Somehow applying DTD to the XML parser of the .Net framework
            // makes parsing slow.
            XmlElement plst = xmlDocument.CreateElement("plist");
            xmlDocument.AppendChild(plst);
            XmlElement dict = xmlDocument.CreateElement("dict");
            plst.AppendChild(dict);

            foreach (KeyValuePair<string, string> kvp in dictionary)
            {
                XmlElement theKey = xmlDocument.CreateElement("key");
                theKey.InnerText = kvp.Key.Trim();
                dict.AppendChild(theKey);

                if (kvp.Value.StartsWith("ARRAY:"))
                {
                    string stringToExplode = kvp.Value.Remove(0, 6);
                    string[] explodedStrings = stringToExplode.Split(", ".ToCharArray());
                    XmlElement theArray = xmlDocument.CreateElement("array");
                    foreach (string item in explodedStrings)
                    {
                        if (item.Length > 0)
                        {
                            XmlElement theString = xmlDocument.CreateElement("string");
                            theString.InnerText = item;
                            theArray.AppendChild(theString);
                        }
                    }
                    dict.AppendChild(theArray);
                }
                else
                {
                    XmlElement theString = xmlDocument.CreateElement("string");
                    theString.InnerText = kvp.Value.Trim();

                    if (theString.InnerText.Length == 0)
                    {
                        theString.IsEmpty = true;
                    }

                    dict.AppendChild(theString);
                }
            }
            XmlTextWriter writer = new XmlTextWriter(filename, Encoding.UTF8);
            writer.Formatting = Formatting.Indented;
            xmlDocument.WriteContentTo(writer);
            writer.Close();
        }
示例#22
0
        protected static XmlDocument ValidateSchema(string docTypeAlias, XmlDocument xmlDoc)
        {
			// check if doctype is defined in schema else add it
			// can't edit the doctype of an xml document, must create a new document

			var doctype = xmlDoc.DocumentType;
			var subset = doctype.InternalSubset;
			if (!subset.Contains(string.Format("<!ATTLIST {0} id ID #REQUIRED>", docTypeAlias)))
			{
				subset = string.Format("<!ELEMENT {0} ANY>\r\n<!ATTLIST {0} id ID #REQUIRED>\r\n{1}", docTypeAlias, subset);
				var xmlDoc2 = new XmlDocument();
				doctype = xmlDoc2.CreateDocumentType("root", null, null, subset);
				xmlDoc2.AppendChild(doctype);
				var root = xmlDoc2.ImportNode(xmlDoc.DocumentElement, true);
				xmlDoc2.AppendChild(root);

				// apply
				xmlDoc = xmlDoc2;
			}

			return xmlDoc;
        }
        /// <summary>
        /// Internal method which generates the RDF/Json Output for a Graph
        /// </summary>
        /// <param name="context">Writer Context</param>
        private void GenerateOutput(RdfXmlWriterContext context)
        {
            context.UseDtd = this._useDTD;

            //Create required variables
            int nextNamespaceID = 0;
            List<String> tempNamespaces = new List<String>();

            //Always force RDF Namespace to be correctly defined
            context.Graph.NamespaceMap.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));

            //Create an XML Document
            XmlDocument doc = new XmlDocument();
            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(decl);

            //Create the DOCTYPE declaration and the rdf:RDF element
            StringBuilder entities = new StringBuilder();
            XmlElement rdf = doc.CreateElement("rdf:RDF", NamespaceMapper.RDF);
            if (context.Graph.BaseUri != null)
            {
                XmlAttribute baseUri = doc.CreateAttribute("xml:base");
                baseUri.Value = context.Graph.BaseUri.ToString();
                rdf.Attributes.Append(baseUri);
            }

            XmlAttribute ns;
            String uri;
            entities.Append('\n');
            foreach (String prefix in context.Graph.NamespaceMap.Prefixes)
            {
                uri = context.Graph.NamespaceMap.GetNamespaceUri(prefix).ToString();
                if (!prefix.Equals(String.Empty))
                {
                    entities.AppendLine("\t<!ENTITY " + prefix + " '" + uri + "'>");
                    ns = doc.CreateAttribute("xmlns:" + prefix);
                    ns.Value = uri.Replace("'", "&apos;");
                }
                else
                {
                    ns = doc.CreateAttribute("xmlns");
                    ns.Value = uri;
                }
                rdf.Attributes.Append(ns);
            }
            if (context.UseDtd)
            {
                XmlDocumentType doctype = doc.CreateDocumentType("rdf:RDF", null, null, entities.ToString());
                doc.AppendChild(doctype);
            }
            doc.AppendChild(rdf);

            //Find the Collections
            if (this._compressionLevel >= WriterCompressionLevel.More)
            {
                WriterHelper.FindCollections(context);
            }

            //Find the Type References
            Dictionary<INode, String> typerefs = this.FindTypeReferences(context, ref nextNamespaceID, tempNamespaces, doc);

            //Get the Triples as a Sorted List
            List<Triple> ts = context.Graph.Triples.Where(t => !context.TriplesDone.Contains(t)).ToList();
            ts.Sort();

            //Variables we need to track our writing
            INode lastSubj, lastPred;
            lastSubj = lastPred = null;
            XmlElement subj, pred;

            //Initialise stuff to keep the compiler happy
            subj = doc.CreateElement("rdf:Description", NamespaceMapper.RDF);
            pred = doc.CreateElement("temp");

            for (int i = 0; i < ts.Count; i++)
            {
                Triple t = ts[i];
                if (context.TriplesDone.Contains(t)) continue; //Skip if already done

                if (lastSubj == null || !t.Subject.Equals(lastSubj))
                {
                    //Start a new set of Triples
                    //Validate Subject
                    //Use a Type Reference if applicable
                    if (typerefs.ContainsKey(t.Subject))
                    {
                        String tref = typerefs[t.Subject];
                        String tprefix;
                        if (tref.StartsWith(":"))
                        {
                            tprefix = String.Empty;
                        }
                        else if (tref.Contains(":"))
                        {
                            tprefix = tref.Substring(0, tref.IndexOf(':'));
                        }
                        else
                        {
                            tprefix = String.Empty;
                        } 
                        subj = doc.CreateElement(tref, context.Graph.NamespaceMap.GetNamespaceUri(tprefix).ToString());
                    }
                    else
                    {
                        subj = doc.CreateElement("rdf:Description", NamespaceMapper.RDF);
                    }

                    //Write out the Subject
                    doc.DocumentElement.AppendChild(subj);
                    lastSubj = t.Subject;

                    //Apply appropriate attributes
                    switch (t.Subject.NodeType)
                    {
                        case NodeType.GraphLiteral:
                            throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));
                        case NodeType.Literal:
                            throw new RdfOutputException(WriterErrorMessages.LiteralSubjectsUnserializable("RDF/XML"));
                        case NodeType.Blank:
                            if (context.Collections.ContainsKey(t.Subject))
                            {
                                this.GenerateCollectionOutput(context, t.Subject, subj, ref nextNamespaceID, tempNamespaces, doc);
                            }
                            else
                            {
                                XmlAttribute nodeID = doc.CreateAttribute("rdf:nodeID", NamespaceMapper.RDF);
                                nodeID.Value = ((IBlankNode)t.Subject).InternalID;
                                subj.Attributes.Append(nodeID);
                            }
                            break;
                        case NodeType.Uri:
                            this.GenerateUriOutput(context, (IUriNode)t.Subject, "rdf:about", tempNamespaces, subj, doc);
                            break;
                        default:
                            throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                    }

                    //Write the Predicate
                    pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                    subj.AppendChild(pred);
                    lastPred = t.Predicate;
                }
                else if (lastPred == null || !t.Predicate.Equals(lastPred))
                {
                    //Write the Predicate
                    pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                    subj.AppendChild(pred);
                    lastPred = t.Predicate;
                }

                //Write the Object
                //Create an Object for the Object
                switch (t.Object.NodeType)
                {
                    case NodeType.Blank:
                        if (pred.HasChildNodes || pred.HasAttributes)
                        {
                            //Require a new Predicate
                            pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                            subj.AppendChild(pred);
                        }

                        if (context.Collections.ContainsKey(t.Object))
                        {
                            //Output a Collection
                            this.GenerateCollectionOutput(context, t.Object, pred, ref nextNamespaceID, tempNamespaces, doc);
                        }
                        else
                        {
                            //Terminate the Blank Node triple by adding a rdf:nodeID attribute
                            XmlAttribute nodeID = doc.CreateAttribute("rdf:nodeID", NamespaceMapper.RDF);
                            nodeID.Value = ((IBlankNode)t.Object).InternalID;
                            pred.Attributes.Append(nodeID);
                        }

                        //Force a new Predicate after Blank Nodes
                        lastPred = null;

                        break;

                    case NodeType.GraphLiteral:
                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML"));

                    case NodeType.Literal:
                        ILiteralNode lit = (ILiteralNode)t.Object;

                        if (pred.HasChildNodes || pred.HasAttributes)
                        {
                            //Require a new Predicate
                            pred = this.GeneratePredicateNode(context, t.Predicate, ref nextNamespaceID, tempNamespaces, doc, subj);
                            subj.AppendChild(pred);
                        }

                        this.GenerateLiteralOutput(context, lit, pred, doc);

                        //Force a new Predicate Node after Literals
                        lastPred = null;

                        break;
                    case NodeType.Uri:

                        this.GenerateUriOutput(context, (IUriNode)t.Object, "rdf:resource", tempNamespaces, pred, doc);

                        //Force a new Predicate Node after URIs
                        lastPred = null;

                        break;
                    default:
                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("RDF/XML"));
                }

                context.TriplesDone.Add(t);
            }

            //Check we haven't failed to output any collections
            foreach (KeyValuePair<INode, OutputRdfCollection> pair in context.Collections)
            {
                if (!pair.Value.HasBeenWritten)
                {
                    if (typerefs.ContainsKey(pair.Key))
                    {
                        String tref = typerefs[pair.Key];
                        String tprefix;
                        if (tref.StartsWith(":")) 
                        {
                            tref = tref.Substring(1);
                            tprefix = String.Empty;
                        }
                        else if (tref.Contains(":"))
                        {
                            tprefix = tref.Substring(0, tref.IndexOf(':'));
                        }
                        else
                        {
                            tprefix = String.Empty;
                        }
                        subj = doc.CreateElement(tref, context.Graph.NamespaceMap.GetNamespaceUri(tprefix).ToString());

                        doc.DocumentElement.AppendChild(subj);

                        this.GenerateCollectionOutput(context, pair.Key, subj, ref nextNamespaceID, tempNamespaces, doc);
                    }
                    else
                    {
                        //Generate an rdf:Description Node with a rdf:nodeID on it
                        XmlElement colNode = doc.CreateElement("rdf:Description");
                        XmlAttribute nodeID = doc.CreateAttribute("rdf:nodeID");
                        nodeID.Value = ((IBlankNode)pair.Key).InternalID;
                        colNode.Attributes.Append(nodeID);
                        doc.DocumentElement.AppendChild(colNode);
                        this.GenerateCollectionOutput(context, pair.Key, colNode, ref nextNamespaceID, tempNamespaces, doc);
                        //throw new RdfOutputException("Failed to output a Collection due to an unknown error");
                    }
                }
            }

            //Save to the Output Stream
            InternalXmlWriter writer = new InternalXmlWriter();
            writer.Save(context.Output, doc);

            //Get rid of the Temporary Namespace
            foreach (String tempPrefix in tempNamespaces)
            {
                context.Graph.NamespaceMap.RemoveNamespace(tempPrefix);
            }
        }
示例#24
0
        private Boolean validateXml(FileInfo fiFile)
        {
            isValid = true;
              string strDTDPath = "C:/Clients/Globus/GlobusWebsite/GlobusWebsite/XmlData/Tour.dtd";
            //HttpContext.Current.Server.MapPath("~/XmlData/Tour.dtd").Replace("\\", "/");

              try
              {

            oDoc = new XmlDocument();
            oDoc.Load(fiFile.FullName);
            oDoc.InsertBefore(oDoc.CreateDocumentType("Tour", null, String.Format("file:///{0}", strDTDPath), null), oDoc.DocumentElement);
            XmlReaderSettings settings = new XmlReaderSettings();
            //settings.ProhibitDtd = false;
            settings.DtdProcessing = DtdProcessing.Parse;
            settings.ValidationType = ValidationType.DTD;
            settings.ValidationEventHandler += new ValidationEventHandler(delegate(object sender, ValidationEventArgs args)
            {
              isValid = false;
              dictInvalidFiles.Add(fiFile.FullName.Substring(fiFile.FullName.LastIndexOf("\\") + 1), args.Message);
            });
            XmlReader validator = XmlReader.Create(new StringReader(oDoc.OuterXml), settings);
            while (validator.Read())
            {
            }
            validator.Close();

              }
              catch (Exception ex)
              {
            isValid = false;
              }

              lValidFiles += isValid ? 1 : 0;
              lInvalidFiles += isValid ? 0 : 1;

              return isValid;
        }
示例#25
0
		/// <summary>
		/// Creates a reader to read and validate the xml data for the
		/// property element specified
		/// </summary>
		/// <param name="propertyElement">The xml property element</param>
		private void CreateValidatingReader(XmlElement propertyElement)
		{
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(propertyElement.OuterXml);
		    if (doc.DocumentElement != null)
		        doc.InsertBefore(
		            doc.CreateDocumentType(doc.DocumentElement.Name, null, null, GetDTD(doc.DocumentElement.Name)),
		            doc.DocumentElement);
		    XmlReaderSettings settings = new XmlReaderSettings();
			settings.CheckCharacters = true;
			settings.ConformanceLevel = ConformanceLevel.Auto;
			settings.IgnoreComments = true;
			settings.IgnoreWhitespace = true;
			settings.ValidationType = ValidationType.DTD;
			settings.ValidationEventHandler += ValidationHandler;
			_reader = XmlReader.Create(new XmlTextReader(new StringReader(doc.OuterXml)), settings);

            
			_reader.Read();
		}
 /// <summary>
 /// Validats the given xml document
 /// </summary>
 /// <param name="xmlDocument">The xml document object</param>
 /// <exception cref="InvalidXmlDefinitionException">Thrown if there
 /// is a validation failure</exception>
 public void ValidateDocument(XmlDocument xmlDocument)
 {
     _xmlDocument = xmlDocument;
     _xmlDocument.InsertBefore(
         xmlDocument.CreateDocumentType(xmlDocument.DocumentElement.Name, null, null,
                                        GetDTD(xmlDocument.DocumentElement.Name)), xmlDocument.DocumentElement);
     ValidateCurrentDocument();
 }
示例#27
0
        //Creates a XML-Document with namespaces, testsubject, testergroup  
        public void createEmptyEarlGraph(MediaType chosenMediaType)
        {
            this.mediaType = chosenMediaType;
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            baseUri = "XMLFile1.xml";
            earl = new XmlDocument();
            XmlDeclaration xdeclaration = earl.CreateXmlDeclaration("1.0", "utf-8", null);
            nsmgr = new XmlNamespaceManager(earl.NameTable);
            nsmgr.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
            nsmgr.AddNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
            nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema#");
            nsmgr.AddNamespace("xml", "http://www.w3.org/XML/1998/namespace");
            nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
            nsmgr.AddNamespace("earl", "http://www.w3.org/ns/earl#");
            nsmgr.AddNamespace("foaf", "http://xmlns.com/foaf/spec/");
            nsmgr.AddNamespace("dct", "http://purl.org/dc/terms/");
            nsmgr.AddNamespace("doap", "http://usefulinc.com/ns/doap#");
            XmlDocumentType doctype;
            doctype = earl.CreateDocumentType("rdf:RDF", null, null, @"
    <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>
    <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema#'>
    <!ENTITY xsd 'http://www.w3.org/2001/XMLSchema#'>
    <!ENTITY xml 'http://www.w3.org/XML/1998/namespace'>
    <!ENTITY dc 'http://purl.org/dc/elements/1.1/'>
    <!ENTITY earl 'http://www.w3.org/ns/earl#'>
    <!ENTITY foaf 'http://xmlns.com/foaf/spec/'>
    <!ENTITY dct 'http://purl.org/dc/terms/'>
    <!ENTITY doap 'http://usefulinc.com/ns/doap#'>");
            earl.AppendChild(doctype);


            root = earl.CreateElement("rdf", "RDF", nsmgr.LookupNamespace("rdf"));

            foreach (String prefix in nsmgr)
            {
                if (!String.IsNullOrWhiteSpace(prefix)
                    && !prefix.Equals("xmlns")
                    )
                {
                    var uri = nsmgr.LookupNamespace(prefix);
                    if (!String.IsNullOrWhiteSpace(uri))
                        root.SetAttribute("xmlns:" + prefix, uri);
                }
            }
            earl.AppendChild(root);

            software2 = earl.CreateElement("earl", "Software", nsmgr.LookupNamespace("earl"));
            software2.SetAttributeNode("ID", nsmgr.LookupNamespace("rdf"));
            software2.SetAttribute("ID", "pruefdialog");
            root.AppendChild(software2);

            XmlElement desc = earl.CreateElement("dct", "description", nsmgr.LookupNamespace("dct"));
            desc.AppendChild(earl.CreateTextNode("Ein Dialog zur Bewertung taktiler Grafiken"));
            desc.SetAttributeNode("lang", nsmgr.LookupNamespace("xml"));
            desc.SetAttribute("lang", "de");
            software2.AppendChild(desc);

            XmlElement title = earl.CreateElement("dct", "title", nsmgr.LookupNamespace("dct"));
            title.AppendChild(earl.CreateTextNode("Pruefdialog taktile Grafiken"));
            title.SetAttributeNode("lang", nsmgr.LookupNamespace("xml"));
            title.SetAttribute("lang", "de");
            software2.AppendChild(title);

            testPerson = earl.CreateElement("foaf", "Person", nsmgr.LookupNamespace("foaf"));
            testPerson.SetAttributeNode("ID", nsmgr.LookupNamespace("rdf"));
            testPerson.SetAttribute("ID", "testperson");

            XmlElement name = earl.CreateElement("foaf", "name", nsmgr.LookupNamespace("foaf"));
            name.AppendChild(earl.CreateTextNode("Max Mustermann"));
            testPerson.AppendChild(name);

            group = earl.CreateElement("foaf", "Group", nsmgr.LookupNamespace("foaf"));
            group.SetAttributeNode("ID", nsmgr.LookupNamespace("rdf"));
            group.SetAttribute("ID", "assertorgroup");
            root.AppendChild(group);

            //TODOOOOOOOO!!!!
            XmlElement descgroup = earl.CreateElement("dct", "title", nsmgr.LookupNamespace("dct"));
            descgroup.AppendChild(earl.CreateTextNode("Max Mustermann und Pruefdialog"));
            group.AppendChild(descgroup);

            XmlElement descAssertorGroup = earl.CreateElement("dct", "description", nsmgr.LookupNamespace("dct"));
            descAssertorGroup.AppendChild(earl.CreateTextNode("Max Mustermann überprüfte die Grafik manuell mit dem Pruefdialog"));
            group.AppendChild(descAssertorGroup);

            XmlElement mainAssertor = earl.CreateElement("earl", "mainAssertor", nsmgr.LookupNamespace("earl"));
            mainAssertor.SetAttributeNode("resource", nsmgr.LookupNamespace("rdf"));
            mainAssertor.SetAttribute("resource", "#"+software2.GetAttribute("ID"));
            group.AppendChild(mainAssertor);

            XmlElement foafMember = earl.CreateElement("foaf", "member", nsmgr.LookupNamespace("foaf"));
            group.AppendChild(foafMember);

            foafMember.AppendChild(testPerson);

            testsubject = earl.CreateElement("earl", "TestSubject", nsmgr.LookupNamespace("earl"));
            testsubject.SetAttributeNode("ID", nsmgr.LookupNamespace("rdf"));
            testsubject.SetAttribute("ID", "testsubject");
            root.AppendChild(testsubject);

            XmlElement bildTitle = earl.CreateElement("dct", "title", nsmgr.LookupNamespace("dct"));
            bildTitle.AppendChild(earl.CreateTextNode("Titel der Grafik"));
            bildTitle.SetAttributeNode("lang", nsmgr.LookupNamespace("xml"));
            bildTitle.SetAttribute("lang", "de");
            testsubject.AppendChild(bildTitle);

            XmlElement mediaType = earl.CreateElement("dct", "description", nsmgr.LookupNamespace("dct"));
            mediaType.AppendChild(earl.CreateTextNode("Die geprüfte Grafik"+"(Medium_"+ chosenMediaType.ToString().Normalize() +")" ));
            testsubject.AppendChild(mediaType);




        }
示例#28
0
 /// <summary>
 /// Create a <see cref="XmlDocumentType"/>
 /// </summary>
 /// <param name="document"></param>
 /// <param name="doctype"></param>
 /// <returns></returns>
 static public XmlDocumentType CreateDocumentType(this XmlDocument document, DocumentType doctype)
 {
     return(document.CreateDocumentType(doctype.Name, doctype.PublicId, doctype.SystemId, doctype.Subset));
 }
示例#29
0
        public void ExportToXML(string aFile)
        {
            XmlDocument lXMLDoc = new XmlDocument();

                    lXMLDoc.AppendChild(lXMLDoc.CreateXmlDeclaration("1.0", "utf-8", ""));
                    lXMLDoc.AppendChild(lXMLDoc.CreateDocumentType("ReportCollection", null, null, null));
                    XmlNode lRootNode = lXMLDoc.CreateNode("element", "report-collection", "");
                    XmlAttribute lDocVer = lXMLDoc.CreateAttribute("version");
                    lDocVer.Value = "rcf0";
                    lRootNode.Attributes.Append(lDocVer);

                    lXMLDoc.AppendChild(lRootNode);
                    RootFolder.BuildXML(lRootNode, lXMLDoc);

                    lXMLDoc.Save(aFile);
        }
示例#30
0
        protected static void ReGenerateSchema(XmlDocument xmlDoc)
        {
            string dtd = DocumentType.GenerateXmlDocumentType();

            // remove current doctype
            XmlNode n = xmlDoc.FirstChild;
            while (n.NodeType != XmlNodeType.DocumentType && n.NextSibling != null)
            {
                n = n.NextSibling;
            }
            if (n.NodeType == XmlNodeType.DocumentType)
            {
                xmlDoc.RemoveChild(n);
            }
            XmlDocumentType docType = xmlDoc.CreateDocumentType("root", null, null, dtd);
            xmlDoc.InsertAfter(docType, xmlDoc.FirstChild);
        }
示例#31
0
		public void GetReady ()
		{
			document = new XmlDocument ();
			docType = document.CreateDocumentType ("book", null, null, "<!ELEMENT book ANY>");
			document.AppendChild (docType);
		}
示例#32
0
        internal static string SearchesToXML(List<Search> searches)
        {
            XmlDocument document = new XmlDocument();
            document.XmlResolver = new BasicXMLResolver();

            document.AppendChild(document.CreateXmlDeclaration("1.0", Encoding.UTF8.WebName, null));
            document.AppendChild(document.CreateDocumentType("XenSearch", "-//XENSEARCH//DTD XENSEARCH 1//EN", "XenSearch-1.dtd", null));

            XmlNode node = document.CreateElement("Searches");
            AddAttribute(document, node, "xmlns", xmlns);
            document.AppendChild(node);

            foreach (Search s in searches)
            {
                node.AppendChild(SearchToXMLNode(document, s));
            }

            StringWriter sw = new StringWriter();
            XmlTextWriter w = new XmlTextWriter(sw);
            try
            {
                w.Formatting = Formatting.Indented;
                w.Indentation = 4;
                w.IndentChar = ' ';

                document.WriteTo(w);
                w.Flush();

                return sw.ToString();
            }
            finally
            {
                w.Close();
                sw.Close();
            }
        }
示例#33
0
		public void IncorrectInternalSubset ()
		{
			XmlDocument doc = new XmlDocument ();
			XmlDocumentType doctype = doc.CreateDocumentType (
				"root", "public-hogehoge", null,
				"invalid_intsubset");
			doctype = doc.CreateDocumentType ("root",
				"public-hogehoge", null, 
				"<!ENTITY % pe1 '>'> <!ELEMENT e EMPTY%pe1;");
		}
示例#34
0
        private void LoadHotKeys(string file)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(file);

            XmlDocumentType docType = doc.CreateDocumentType("GDKML", null, null, null);
            string dtdString = docType.InnerXml;

            XmlElement root = doc["Hotkeys"];

            int count = root.ChildNodes.Count;

            for (int c = 0; c < count; c++)
            {
                XmlElement node = (XmlElement)root.ChildNodes[c];

                if (node.Name == "References")
                {
                    int referenceCount = node.ChildNodes.Count;

                    for (int a = 0; a < referenceCount; a++)
                    {
                        XmlElement child = (XmlElement)node.ChildNodes[a];

                        if (child.Name == "Assembly")
                        {
                            string assembly = Utility.GetAttributeString(child, "file");

                            if (String.IsNullOrEmpty(assembly))
                            {
                                MessageBox.Show("Reference number " + a.ToString() + " does not contain a file name and will not be loaded.", "RunUO: GDK");
                                continue;
                            }

                            assemblies.Add(assembly);
                        }
                        else if (child.Name == "Namespace")
                        {
                            string nmspace = Utility.GetAttributeString(child, "name");

                            if (String.IsNullOrEmpty(nmspace))
                            {
                                MessageBox.Show("Reference number " + a.ToString() + " does not contain a file name and will not be loaded.", "RunUO: GDK");
                                continue;
                            }

                            namespaces.Add(nmspace);
                        }
                    }
                }
                else if (node.Name == "Hotkey" && Utility.GetAttributeBoolean(node, "compile", true))
                {
                    int hotKeyCount = node.ChildNodes.Count;
                    string name = Utility.GetAttributeString(node, "name");

                    if(String.IsNullOrEmpty(name))
                    {
                        MessageBox.Show("A Hotkey does not contain a name and will not be loaded", "RunUO: GDK");
                        continue;
                    }

                    KeyData keyData = new KeyData();

                    keyData.Control = Utility.GetAttributeBoolean(node, "control", false);
                    keyData.Alt = Utility.GetAttributeBoolean(node, "alt", false);
                    keyData.Shift = Utility.GetAttributeBoolean(node, "shift", false);
                    keyData.Key = Utility.GetAttributeKey(node, "key");

                    if (keyData.Key == Keys.None)
                    {
                        MessageBox.Show("Hotkey " + name + " does not have a key specified and will not be loaded.", "RunUO: GDK");
                        continue;
                    }

                    StringBuilder cb = new StringBuilder();

                    for (int a = 0; a < namespaces.Count; a++)
                    {
                        cb.AppendLine("using " + namespaces[a] + ";");
                    }

                    string ctl = keyData.Control.ToString().ToLower();
                    string shf = keyData.Shift.ToString().ToLower();
                    string alt = keyData.Alt.ToString().ToLower();
                    string key = Enum.GetName(typeof(Keys), keyData.Key);

                    cb.AppendLine("");
                    cb.AppendLine("namespace Ultima.GDK {");
                    cb.AppendLine("\tpublic class " + name + "Hotkey {");
                    cb.AppendLine("\t\tpublic " + name + "Hotkey() { }");
                    cb.AppendLine("\t\tpublic KeyData KeyData { get { return new KeyData(" + ctl + ", " + shf + ", " + alt + ", " + "Keys." + key + "); } }");
                    cb.AppendLine("\t\tpublic void Invoke" + "(object sender, HotKeyEventArgs args) { ");
                    cb.AppendLine("\t\t\tif(args == null) {");
                    cb.AppendLine("\t\t\t\tthrow new Exception(\"Delegate arguments are null\");");
                    cb.AppendLine("\t\t\t}");
                    cb.AppendLine("");
                    cb.AppendLine("\t\t\tGump Gump = args.Gump;");
                    cb.AppendLine("\t\t\tDesignerFrame Designer = args.Designer;");
                    cb.AppendLine("");
                    cb.AppendLine("\t\t\t" + node.InnerText.Trim());
                    cb.AppendLine("\t\t}");
                    cb.AppendLine("\t}");
                    cb.AppendLine("}");

                    CSharpCodeProvider csp = new CSharpCodeProvider();
                    ICodeCompiler cc = csp.CreateCompiler();
                    CompilerParameters cp = new CompilerParameters();

                    cp.WarningLevel = 3;

                    cp.ReferencedAssemblies.Add("mscorlib.dll");
                    cp.ReferencedAssemblies.Add("System.dll");
                    cp.ReferencedAssemblies.Add("System.Xml.dll");
                    cp.ReferencedAssemblies.Add("System.Data.dll");
                    cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                    cp.ReferencedAssemblies.Add("Ultima.dll");
                    cp.ReferencedAssemblies.Add("Ultima.GDK.dll");
                    cp.ReferencedAssemblies.Add("RunUO GDK.exe");

                    for (int a = 0; a < assemblies.Count; a++)
                    {
                        cp.ReferencedAssemblies.Add(assemblies[a]);
                    }

                    cp.CompilerOptions = "/target:library /optimize";
                    cp.GenerateExecutable = false;
                    cp.GenerateInMemory = false;

                    string outputAssembly = Application.StartupPath + "\\HotkeyAssemblies\\" + name + "Hotkey.dll";

                    if(!Directory.Exists(Path.GetDirectoryName(outputAssembly)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(outputAssembly));
                    }

                    cp.OutputAssembly = outputAssembly;

                    System.CodeDom.Compiler.TempFileCollection tfc = new TempFileCollection(Application.StartupPath, false);
                    CompilerResults cr = new CompilerResults(tfc);

                    cr = cc.CompileAssemblyFromSource(cp, cb.ToString());

                    if (cr.Errors.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();

                        sb.AppendLine("An error occured while compiling Hotkey: " + name + "\n");

                        for (int b = 0; b < cr.Errors.Count; b++)
                        {
                            sb.AppendLine(cr.Errors[b].ToString());
                        }

                        MessageBox.Show(sb.ToString(), "RunUO: GDK");
                        continue;
                    }
                }
            }

            LoadAssemblies(Application.StartupPath + "\\HotkeyAssemblies\\");
        }
示例#35
0
 /// <summary>
 /// Create a <see cref="XmlDocumentType"/> without any Id
 /// </summary>
 /// <param name="document"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 static public XmlDocumentType CreateDocumentType(this XmlDocument document, string name)
 {
     return(document.CreateDocumentType(name, null, null));
 }