Ejemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Project");
                writer.WriteStartElement("Items");

                Dictionary<int, sProject> projectList;
                DB.LoadProject(out projectList);

                foreach (KeyValuePair<int, sProject> item in projectList)
                {
                    writer.WriteStartElement("Item");
                    writer.WriteAttributeString("uid", item.Key.ToString());
                    writer.WriteAttributeString("name", item.Value.name);
                    writer.WriteEndElement();
                }

                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
Ejemplo n.º 2
0
        public static void OutputFunctionNames(bool compact, string k_test_results_path, string file_name, string[] script_functions)
        {
            using (var t = new System.Xml.XmlTextWriter(System.IO.Path.Combine(k_test_results_path, file_name), System.Text.Encoding.ASCII))
            {
                t.Indentation = 1;
                t.IndentChar  = '\t';
                t.Formatting  = System.Xml.Formatting.Indented;

                t.WriteStartDocument();
                t.WriteStartElement("Functions");
                for (int x = 0; x < script_functions.Length; x++)
                {
                    if (script_functions[x] != "123")
                    {
                        t.WriteStartElement("entry");
                        t.WriteAttributeString("key", "0x" + x.ToString("X3"));
                        t.WriteAttributeString("value", script_functions[x]);
                        t.WriteEndElement();
                    }
                    else if (!compact)
                    {
                        t.WriteStartElement("entry");
                        t.WriteAttributeString("key", "0x" + x.ToString("X3"));
                        t.WriteAttributeString("value", "UNKNOWN");
                        t.WriteEndElement();
                    }
                }
                t.WriteEndElement();
                t.WriteEndDocument();
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Returns the list of features this plug-in supports: like Worklist, CurveData, Attachment_Type, Attachment_Path</summary>
        protected virtual string ReturnSupportedFeatures()
        {
            //- Example -
            //<?xml version="1.0" encoding="utf-16"?>
            //<ndd>
            //    <Command Type="SupportedFeatures">
            //        <Parameter Name="SearchPatients"></Parameter>
            //    </Command>
            //</ndd>


            StringBuilder sb = new System.Text.StringBuilder();

            using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(new System.IO.StringWriter(sb, CultureInfo.InvariantCulture)))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("ndd");
                xmlWriter.WriteStartElement("Command");
                xmlWriter.WriteAttributeString("Type", Commands.SupportedFeatures.Command);

                foreach (string strFeature in GetSupportedFeatures())
                {
                    xmlWriter.WriteStartElement("Parameter");
                    xmlWriter.WriteAttributeString("Name", strFeature);
                    xmlWriter.WriteValue("True");
                    xmlWriter.WriteEndElement();//parameter
                }
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
                xmlWriter.Flush();
                xmlWriter.Close();
                return(sb.ToString());
            }
        }
Ejemplo n.º 4
0
        public void ToXml(System.Xml.XmlTextWriter writer)
        {
            // FIXME: if (this.IsOr) rc_package_dep_or_slist_to_xml_node ()

            writer.WriteStartElement("dep");

            using (RC.PackageSpec spec = Spec) {
                writer.WriteAttributeString("name", spec.Name);

                if (this.Relation != PackageRelation.Any)
                {
                    writer.WriteAttributeString("op", Package.RelationToString(this.Relation, 0));

                    if (spec.HasEpoch)
                    {
                        writer.WriteAttributeString("epoch", System.Xml.XmlConvert.ToString(spec.Epoch));
                    }

                    if (spec.Version != null)
                    {
                        writer.WriteAttributeString("version", spec.Version);
                    }

                    if (spec.Release != null)
                    {
                        writer.WriteAttributeString("release", spec.Release);
                    }
                }
            }

            writer.WriteEndElement();
        }
        new private string ToXmlBaseString(bool useXMLLang, System.Xml.XmlTextWriter xmlOutput)
        {
            if (xmlOutput == null)
            {
                string baseElement = base.ToXmlString();
                string element     = "<CustomField ";
//				element += "guid=\"" + m_guid + "\" ";
                element += "wsSelector=\"" + m_wsSelector + "\" ";
                element += "big=\"" + m_big + "\" ";
                element += "flid=\"" + m_flid + "\" ";
                element += "class=\"" + m_class + "\" ";
                element += "uiclass=\"" + m_uiClass + "\" ";
                element += ">" + System.Environment.NewLine;
                element += baseElement + System.Environment.NewLine;
                element += "</CustomField>";
                return(element);
            }
            if (xmlOutput != null)
            {
                xmlOutput.WriteStartElement("CustomField");
//				xmlOutput.WriteAttributeString("guid", m_guid);
                xmlOutput.WriteAttributeString("wsSelector", m_wsSelector.ToString());
                xmlOutput.WriteAttributeString("big", m_big.ToString());
                xmlOutput.WriteAttributeString("flid", m_flid.ToString());
                xmlOutput.WriteAttributeString("class", m_class);
                xmlOutput.WriteAttributeString("uiclass", m_uiClass);
                base.ToXmlBaseString(useXMLLang, xmlOutput);
                xmlOutput.WriteEndElement();
            }
            return("");
        }
Ejemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType     = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Project");
                writer.WriteStartElement("Items");

                Dictionary <int, sProject> projectList;
                DB.LoadProject(out projectList);

                foreach (KeyValuePair <int, sProject> item in projectList)
                {
                    writer.WriteStartElement("Item");
                    writer.WriteAttributeString("uid", item.Key.ToString());
                    writer.WriteAttributeString("name", item.Value.name);
                    writer.WriteEndElement();
                }

                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 保存配置到配置文件
        /// </summary>
        /// <param name="fileName">配置文件名</param>
        public virtual void SaveConfig(String fileName)
        {
            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(fileName, Encoding.UTF8);

            try
            {
                writer.Formatting = System.Xml.Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement("Jeelu.WordSegmentor");


                foreach (CfgItem item in GetCfgItems())
                {
                    writer.WriteComment(item.Comment);
                    writer.WriteStartElement("Item");
                    writer.WriteAttributeString("Name", item.Pi.Name);
                    writer.WriteAttributeString("Value", item.Pi.GetValue(this, null).ToString());
                    writer.WriteEndElement(); //Item
                }

                writer.WriteEndElement(); //Jeelu.WordSegmentor
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
            catch (Exception e)
            {
                WriteLog(String.Format("Save config fail, errmsg:{0}", e.Message));
            }
        }
Ejemplo n.º 8
0
 protected virtual void WriteStart(System.Xml.XmlTextWriter wr)
 {
     _cnt++;
     wr.WriteStartElement("l");
     wr.WriteAttributeString("tick", _tick.ToString());
     wr.WriteAttributeString("object", GetLockString(_lock_obj));
     System.Diagnostics.Debug.WriteLine(string.Format("thread[{2}]{0}: {1}", _cnt, GetLockString(_lock_obj), _sb.GetHashCode()));
 }
Ejemplo n.º 9
0
        public Task <byte[]> CreatePlayListAsync(Uri baseuri, IEnumerable <KeyValuePair <string, string> > parameters, CancellationToken cancellationToken)
        {
            var queries = String.Join("&", parameters.Select(kv => Uri.EscapeDataString(kv.Key) + "=" + Uri.EscapeDataString(kv.Value)));
            var stream  = new System.IO.StringWriter();
            var xml     = new System.Xml.XmlTextWriter(stream);

            xml.Formatting = System.Xml.Formatting.Indented;
            xml.WriteStartElement("ASX");
            xml.WriteAttributeString("version", "3.0");
            if (Channels.Count > 0)
            {
                xml.WriteElementString("Title", Channels[0].ChannelInfo.Name);
            }
            foreach (var c in Channels)
            {
                string name        = c.ChannelInfo.Name;
                string contact_url = null;
                if (c.ChannelInfo.URL != null)
                {
                    contact_url = c.ChannelInfo.URL;
                }
                var stream_url = new UriBuilder(baseuri);
                stream_url.Scheme = scheme;
                if (stream_url.Path[stream_url.Path.Length - 1] != '/')
                {
                    stream_url.Path += '/';
                }
                stream_url.Path +=
                    c.ChannelID.ToString("N").ToUpper() +
                    c.ChannelInfo.ContentExtension;
                if (queries != "")
                {
                    stream_url.Query = queries;
                }
                xml.WriteStartElement("Entry");
                xml.WriteElementString("Title", name);
                if (contact_url != null && contact_url != "")
                {
                    xml.WriteStartElement("MoreInfo");
                    xml.WriteAttributeString("href", contact_url);
                    xml.WriteEndElement();
                }
                xml.WriteStartElement("Ref");
                xml.WriteAttributeString("href", stream_url.Uri.ToString());
                xml.WriteEndElement();
                xml.WriteEndElement();
            }
            xml.WriteEndElement();
            xml.Close();
            var res = stream.ToString();

            try {
                return(Task.FromResult(System.Text.Encoding.GetEncoding(932).GetBytes(res)));
            }
            catch (System.Text.EncoderFallbackException) {
                return(Task.FromResult(System.Text.Encoding.UTF8.GetBytes(res)));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Save options.
        /// </summary>
        /// <param name="filePath">File name to save options to.</param>
        public void Serialize(string filePath)
        {
            System.Text.Encoding           encoding       = System.Text.Encoding.GetEncoding("ISO-8859-1");
            global::System.IO.MemoryStream newFileContent = null;
            try
            {
                newFileContent = new global::System.IO.MemoryStream();
                global::System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(newFileContent, encoding);
                xmlWriter.Formatting = System.Xml.Formatting.Indented;
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("ViewModelOptions");

                // write attributes
                xmlWriter.WriteAttributeString("errorCategoryVisible", this.ErrorCategoryVisible.ToString());
                xmlWriter.WriteAttributeString("warningCategoryVisible", this.WarningCategoryVisible.ToString());
                xmlWriter.WriteAttributeString("infoCategoryVisible", this.InfoCategoryVisible.ToString());
                xmlWriter.WriteAttributeString("filteredCategoryVisible", this.FilteredCategoryVisible.ToString());

                SerializeElements(xmlWriter);
                xmlWriter.WriteEndElement();

                xmlWriter.Flush();
                if (newFileContent != null)
                {
                    // Only write the content if there's no error encountered during serialization.
                    global::System.IO.FileStream fileStream = null;
                    try
                    {
                        fileStream = new global::System.IO.FileStream(filePath, global::System.IO.FileMode.Create, global::System.IO.FileAccess.Write, global::System.IO.FileShare.None);
                        using (global::System.IO.BinaryWriter writer = new global::System.IO.BinaryWriter(fileStream, encoding))
                        {
                            try
                            {
                                writer.Write(newFileContent.ToArray());
                            }
                            finally
                            {
                                fileStream = null;
                            }
                        }
                    }
                    finally
                    {
                        if (fileStream != null)
                        {
                            fileStream.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (newFileContent != null)
                {
                    newFileContent.Dispose();
                }
            }
        }
Ejemplo n.º 11
0
        public void GetXinhuaGraphicXml(System.Xml.XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("Element");
            xmlWriter.WriteAttributeString("type", DynamicObjectType.DynTagDef);
            xmlWriter.WriteAttributeString("TestPointName", this.pointName);
            xmlWriter.WriteAttributeString("TagDefType", this.tagType.ToString());

            xmlWriter.WriteEndElement();
        }
Ejemplo n.º 12
0
 public void GetXinhuaGraphicXml(System.Xml.XmlTextWriter xmlWriter)
 {
     xmlWriter.WriteStartElement("Element");
     xmlWriter.WriteAttributeString("type", DynamicObjectType.DynValueOut);
     xmlWriter.WriteAttributeString("TestPointName", this.pointName);
     xmlWriter.WriteAttributeString("DomainName", "Actual Value");
     xmlWriter.WriteAttributeString("Align", this.alignment.ToString());
     xmlWriter.WriteEndElement();
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Write the attributes of the tag specified
 /// </summary>
 /// <param name="p_Cell"></param>
 /// <param name="p_Position"></param>
 /// <param name="p_Export"></param>
 /// <param name="p_Writer"></param>
 /// <param name="p_ElementTagName"></param>
 protected override void ExportHTML_Attributes(Cells.ICellVirtual p_Cell, Position p_Position, IHTMLExport p_Export, System.Xml.XmlTextWriter p_Writer, string p_ElementTagName)
 {
     base.ExportHTML_Attributes(p_Cell, p_Position, p_Export, p_Writer, p_ElementTagName);
     if (p_ElementTagName == "img")
     {
         p_Writer.WriteAttributeString("align", Utility.ContentToHorizontalAlignment(ImageAlignment).ToString().ToLower());
         p_Writer.WriteAttributeString("src", p_Export.ExportImage(Image));
     }
 }
        void VsICoreAnalyzerDescription.SaveConfiguration(System.Xml.XmlTextWriter writer, VsICoreAnalyzerConfiguration config)
        {
            VsEdgeDetectionConfiguration cfg = (VsEdgeDetectionConfiguration)config;

            if (cfg != null)
            {
                writer.WriteAttributeString("ThresholdStrong", cfg.ThresholdStrong.ToString());
                writer.WriteAttributeString("ThresholdWeak", cfg.ThresholdWeak.ToString());
            }
        }
Ejemplo n.º 15
0
        internal void SaveToXml(System.Xml.XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("Action");
            xmlWriter.WriteAttributeString("Filename", this.Filename);
            xmlWriter.WriteAttributeString("Id", this.Id);
            xmlWriter.WriteAttributeString("Points", this.Points.ToString());
            xmlWriter.WriteAttributeString("Type", this.Type.ToString());

            xmlWriter.WriteEndElement();
        }
Ejemplo n.º 16
0
        void VsICoreAnalyzerDescription.SaveConfiguration(System.Xml.XmlTextWriter writer, VsICoreAnalyzerConfiguration config)
        {
            VsMotionDetectionConfiguration cfg = (VsMotionDetectionConfiguration)config;

            if (cfg != null)
            {
                writer.WriteAttributeString("ThresholdAlpha", cfg.ThresholdAlpha.ToString());
                writer.WriteAttributeString("ThresholdSigma", cfg.ThresholdSigma.ToString());
            }
        }
Ejemplo n.º 17
0
        protected virtual void SaveToFile(DataSet pDataSet)
        {
            if (m_FileName == null)
            {
                throw new ApplicationException("FileName is null");
            }

            byte[] completeByteArray;
            using (System.IO.MemoryStream fileMemStream = new System.IO.MemoryStream())
            {
                System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(fileMemStream, System.Text.Encoding.UTF8);

                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("filedataset", c_DataNamespace);

                xmlWriter.WriteStartElement("header", c_DataNamespace);
                //File Version
                xmlWriter.WriteAttributeString(c_FileVersion, c_FileVersionNumber.ToString());
                //Data Version
                xmlWriter.WriteAttributeString(c_DataVersion, GetDataVersion().ToString());
                //Data Format
                xmlWriter.WriteAttributeString(c_DataFormat, ((int)mSaveDataFormat).ToString());
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("data", c_DataNamespace);

                byte[] xmlByteArray;
                using (System.IO.MemoryStream xmlMemStream = new System.IO.MemoryStream())
                {
                    StreamDataSet.Write(xmlMemStream, pDataSet, mSaveDataFormat);
                    //pDataSet.WriteXml(xmlMemStream);

                    xmlByteArray = xmlMemStream.ToArray();
                    xmlMemStream.Close();
                }

                xmlWriter.WriteBase64(xmlByteArray, 0, xmlByteArray.Length);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();

                xmlWriter.Flush();

                completeByteArray = fileMemStream.ToArray();
                fileMemStream.Close();
            }

            //se tutto ?andato a buon fine scrivo effettivamente il file
            using (System.IO.FileStream fileStream = new System.IO.FileStream(m_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                fileStream.Write(completeByteArray, 0, completeByteArray.Length);
                fileStream.Close();
            }
        }
Ejemplo n.º 18
0
        public void GetXinhuaGraphicXml(System.Xml.XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("Element");
            xmlWriter.WriteAttributeString("type", DynamicObjectType.DynDiColor);
            xmlWriter.WriteAttributeString("TestPointName", this.testPointName);
            xmlWriter.WriteAttributeString("DomainName", "Actual Value");
            xmlWriter.WriteAttributeString("Color0", ColorHelper.ColorToString(this.color0));
            xmlWriter.WriteAttributeString("Color1", ColorHelper.ColorToString(this.color1));

            xmlWriter.WriteEndElement();
        }
Ejemplo n.º 19
0
    protected virtual void OnButtonSaveGamesFileClicked(object sender, System.EventArgs e)
    {
        var saveDialog = new FileChooserDialog("Save Games File", this, FileChooserAction.Save,
                                               "Cancel", ResponseType.Cancel, "Save", ResponseType.Accept);

        SetUniqueFileName(saveDialog, Nexus.Settings.Default.GamesFileDirectory, "game_config.xml");
        saveDialog.DoOverwriteConfirmation = true;

        try
        {
            if (saveDialog.Run() == (int)ResponseType.Accept)
            {
                // Save games file
                using (var writer = new System.Xml.XmlTextWriter(saveDialog.Filename,
                                                                 System.Text.Encoding.UTF8))
                {
                    writer.Formatting = System.Xml.Formatting.Indented;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("games");

                    gameStore.Foreach(delegate(TreeModel model, TreePath path, TreeIter iter)
                    {
                        // Save individual game info
                        var gameInfo = (IGameInfo)model.GetValue(iter, 3);

                        writer.WriteStartElement("game");
                        writer.WriteAttributeString("name", gameInfo.GameName);
                        writer.WriteAttributeString("description", gameInfo.GameDescription);

                        gameInfo.Save(writer);

                        writer.WriteEndElement();

                        return(false);
                    });

                    // games
                    writer.WriteEndElement();
                    writer.WriteEndDocument();

                    Nexus.Settings.Default.GamesFileDirectory = System.IO.Path.GetDirectoryName(saveDialog.Filename);
                }
            }
        }
        catch (Exception ex)
        {
            logger.Error("OnButtonSaveGamesFileClicked", ex);
            ShowErrorDialog(ex);
        }
        finally
        {
            saveDialog.Destroy();
        }
    }
Ejemplo n.º 20
0
        private static void AddCommand(string strCommand, System.Xml.XmlTextWriter xmlWriter, string strParamName, string strParamValue)
        {
            xmlWriter.WriteStartElement("Command");
            xmlWriter.WriteAttributeString("Type", strCommand);

            xmlWriter.WriteStartElement("Parameter");
            xmlWriter.WriteAttributeString("Name", strParamName);
            xmlWriter.WriteValue(strParamValue);
            xmlWriter.WriteEndElement(); //Param

            xmlWriter.WriteEndElement(); //command
        }
Ejemplo n.º 21
0
        void VsICoreEncoderDescription.SaveConfiguration(System.Xml.XmlTextWriter writer, object config)
        {
            VsAviEncoderConfiguration cfg = (VsAviEncoderConfiguration)config;

            if (cfg != null)
            {
                writer.WriteAttributeString("ImageWidth", cfg.ImageWidth.ToString());
                writer.WriteAttributeString("ImageHeight", cfg.ImageHeight.ToString());
                writer.WriteAttributeString("CodecsName", cfg.CodecsName);
                writer.WriteAttributeString("Quality", cfg.Quality.ToString());
            }
        }
Ejemplo n.º 22
0
        public string ToXml()
        {
            StringWriter xmlStream = null;

            System.Xml.XmlTextWriter xmlWriter = null;
            try
            {
                xmlStream = new StringWriter();
                xmlWriter = new System.Xml.XmlTextWriter(xmlStream);

                // Start Document Element
                xmlWriter.WriteStartElement("ServiceParameters");

                if (this.PublicKey != null)
                {
                    xmlWriter.WriteStartElement("Item");
                    xmlWriter.WriteAttributeString("key", "PublicKey");
                    xmlWriter.WriteString(this.PublicKey);
                    xmlWriter.WriteEndElement();
                }

                Enumerator enumerator = this.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        xmlWriter.WriteStartElement("Item");
                        xmlWriter.WriteAttributeString("key", enumerator.Current.Key);
                        xmlWriter.WriteCData(enumerator.Current.Value);
                        xmlWriter.WriteEndElement();
                    }
                }
                finally
                {
                    enumerator.Dispose();
                }

                // End Document Element
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();

                return(xmlStream.ToString());
            }
            catch (Exception)
            {
                return(string.Empty);
            }
            finally
            {
                xmlWriter?.Close();
                xmlStream?.Close();
            }
        }
Ejemplo n.º 23
0
		protected virtual void SaveToFile(DataSet pDataSet)
		{
			if (m_FileName == null)
				throw new ApplicationException("FileName is null");
			
			byte[] completeByteArray;
			using (System.IO.MemoryStream fileMemStream = new System.IO.MemoryStream())
			{
				System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(fileMemStream, System.Text.Encoding.UTF8);

				xmlWriter.WriteStartDocument();
				xmlWriter.WriteStartElement("filedataset", c_DataNamespace);

				xmlWriter.WriteStartElement("header", c_DataNamespace);
				//File Version
				xmlWriter.WriteAttributeString(c_FileVersion, c_FileVersionNumber.ToString());
				//Data Version
				xmlWriter.WriteAttributeString(c_DataVersion, GetDataVersion().ToString());
				//Data Format
				xmlWriter.WriteAttributeString(c_DataFormat, ((int)mSaveDataFormat).ToString());
				xmlWriter.WriteEndElement();

				xmlWriter.WriteStartElement("data", c_DataNamespace);

				byte[] xmlByteArray;
				using (System.IO.MemoryStream xmlMemStream = new System.IO.MemoryStream())
				{
					StreamDataSet.Write(xmlMemStream, pDataSet, mSaveDataFormat);
					//pDataSet.WriteXml(xmlMemStream);

					xmlByteArray = xmlMemStream.ToArray();
					xmlMemStream.Close();
				}

				xmlWriter.WriteBase64(xmlByteArray, 0, xmlByteArray.Length);
				xmlWriter.WriteEndElement();

				xmlWriter.WriteEndElement();
				xmlWriter.WriteEndDocument();

				xmlWriter.Flush();
				
				completeByteArray = fileMemStream.ToArray();
				fileMemStream.Close();
			}

			//se tutto è andato a buon fine scrivo effettivamente il file
			using (System.IO.FileStream fileStream = new System.IO.FileStream(m_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
			{
				fileStream.Write(completeByteArray, 0, completeByteArray.Length);
				fileStream.Close();
			}
		}
Ejemplo n.º 24
0
        public void writeGPX(string filename)
        {
            System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx", Encoding.ASCII);

            xw.WriteStartElement("gpx");

            xw.WriteStartElement("trk");

            xw.WriteStartElement("trkseg");

            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

            foreach (Data mod in flightdata)
            {
                xw.WriteStartElement("trkpt");
                xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("ele", mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("time", mod.datetime.ToString("yyyy-MM-ddTHH:mm:sszzzzzz"));
                xw.WriteElementString("course", (mod.model.Orientation.heading).ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("roll", mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("pitch", mod.model.Orientation.tilt.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("mode", mod.mode);

                //xw.WriteElementString("speed", mod.model.Orientation.);
                //xw.WriteElementString("fix", mod.model.Location.altitude);

                xw.WriteEndElement();
            }


            xw.WriteEndElement(); // trkseg
            xw.WriteEndElement(); // trk

            int a = 0;

            foreach (Data mod in flightdata)
            {
                xw.WriteStartElement("wpt");
                xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("name", (a++).ToString());
                xw.WriteEndElement();//wpt
            }

            xw.WriteEndElement(); // gpx

            xw.Close();
        }
Ejemplo n.º 25
0
 public override void WriteKeyStart(string key)
 {
     if (firstKey)
     {
         xmlWriter.WriteStartElement("registry");
         xmlWriter.WriteAttributeString("branch", key);
         firstKey = false;
     }
     else
     {
         xmlWriter.WriteStartElement("key");
         xmlWriter.WriteAttributeString("name", key.Substring(key.LastIndexOf('\\') + 1));
     }
 }
Ejemplo n.º 26
0
 /// <summary>個々の単語の情報をファイル内に書き込みます。</summary>
 /// <param name="w">書き込む単語の情報を格納している 英単語の練習.Word を指定。</param>
 public void writeWordData(英単語の練習.Word w)
 {
     xtw.WriteStartElement("word"); {
         xtw.WriteAttributeString("name", this.escape(w.word + ((w.pron == "")?"":"|" + w.pron)));
         xtw.WriteAttributeString("mean", this.escape(w.mean));
         xtw.WriteStartElement("part"); {
             xtw.WriteAttributeString("value", this.escape(w.part.partString));
             xtw.WriteAttributeString("conjugate", this.escape(w.strConjugate));
         } xtw.WriteEndElement();
         string nm;                //typ nm 参照語の情報を指定する文字列を格納
         int    rwl, exl;          //rwl は参照の、 exl は例文の、数を表します。
         if ((rwl = w.referWord.Count) != 0)
         {
             for (int i = 0; i < rwl; i++)                                    //if( 〜=0)はいらないかも(Count=0になることはない?)
             {
                 refWord rfword = (refWord)w.referWord[i];
                 if ((nm = rfword.word.Trim()) != "")
                 {
                     if (rfword.pron != "")
                     {
                         nm += "|" + rfword.pron;
                     }
                     xtw.WriteStartElement("ref");
                     xtw.WriteAttributeString("type", rfword.typeString);
                     xtw.WriteAttributeString("name", this.escape(nm));
                     if (rfword.mean != "")
                     {
                         xtw.WriteAttributeString("mean", this.escape(rfword.mean));
                     }
                     xtw.WriteAttributeString("part", rfword.part.partString);
                     xtw.WriteEndElement();
                 }
             }
         }
         if ((exl = w.example.Length) != 0)
         {
             for (int i = 0; i < exl; i++)                                   //if( 〜=0)はいらないかも(length=0になることはない?)
             {
                 if (w.example[i].Trim() != "")
                 {
                     xtw.WriteElementString("xmp", this.escape(w.example[i]));
                 }
             }
         }
         xtw.WriteStartElement("exam"); {
             xtw.WriteAttributeString("shutsudai", w.shutsudai.ToString());
             xtw.WriteAttributeString("seikai", w.seikai.ToString());
         } xtw.WriteEndElement();
     } xtw.WriteEndElement();
 }
Ejemplo n.º 27
0
        public string GetXML()
        {
            System.IO.StringWriter strW = new System.IO.StringWriter();
            using (System.Xml.XmlTextWriter xml = new System.Xml.XmlTextWriter(strW))
            {
                xml.WriteStartDocument();
                xml.WriteStartElement(ObjectName);

                #region SYSTEM PROPERTIES


                xml.WriteStartElement("__TimeStamp");
                xml.WriteAttributeString("Type", typeof(DateTime).ToString());
                xml.WriteAttributeString("Value", TimeStamp.ToString());
                //xml.WriteValue(TimeStamp);
                xml.WriteEndElement();

                #endregion

                #region OBJECT PROPERTIES

                LoggableProperties.ForEach(prop =>
                {
                    xml.WriteStartElement(prop.Name);
                    xml.WriteAttributeString("Type", prop.PropInfo.PropertyType.ToString());
                    xml.WriteAttributeString("Value", prop.Value);
                    //xml.WriteValue(prop.Value);
                    xml.WriteEndElement();
                });

                #endregion

                xml.WriteEndElement();
                xml.WriteEndDocument();

                xml.Flush();
                xml.Close();
            }

            strW.Dispose();



            //System.IO.StringReader sr = new System.IO.StringReader(strW.ToString());
            //System.Xml.XmlTextReader xml = new System.Xml.XmlTextReader(sr);



            return(strW.ToString());
        }
Ejemplo n.º 28
0
        public void GetXinhuaGraphicXml(System.Xml.XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("Element");
            xmlWriter.WriteAttributeString("type", LogicObjectType.Poke);
            xmlWriter.WriteAttributeString("X1", Convert.ToString(this.X * 10));
            xmlWriter.WriteAttributeString("Y1", Convert.ToString(this.Y * 10));
            xmlWriter.WriteAttributeString("X2", Convert.ToString((this.X + this.Width) * 10));
            xmlWriter.WriteAttributeString("Y2", Convert.ToString((this.Y + this.Height) * 10));
            xmlWriter.WriteAttributeString("BlockID", this.BlockID.ToString());
            xmlWriter.WriteAttributeString("DynamicOp", this.Dynamics.Count.ToString());
            {
                // 添加动态属性

                xmlWriter.WriteStartElement("Element");
                xmlWriter.WriteAttributeString("type", "DynamicOp");
                foreach (DynamicObject dynamic in this.Dynamics)
                {
                    ILogicGraphicFormat dynamicFormat = dynamic as ILogicGraphicFormat;
                    if (dynamicFormat != null)
                    {
                        dynamicFormat.GetXinhuaGraphicXml(xmlWriter);
                    }
                }
                xmlWriter.WriteEndElement();
            }
            xmlWriter.WriteEndElement();
        }
Ejemplo n.º 29
0
        //e.g. Worklist, CurveData, Attachment_Type, Attachment_Path
        protected virtual string ReturnSearchPatientResult(Dictionary <string, string> parameters)
        {
            using (System.Xml.XmlWriter xmlWriter = new System.Xml.XmlTextWriter(XmlExchangeFile, Encoding.UTF8))
            {
                try
                {
                    xmlWriter.WriteStartDocument();
                    xmlWriter.WriteStartElement("ndd");
                    xmlWriter.WriteStartElement("Command");
                    xmlWriter.WriteAttributeString("Type", Commands.SearchPatientsResult.Command);
                    xmlWriter.WriteEndElement();//command
                    xmlWriter.WriteStartElement("Patients");

                    xmlWriter.WriteStartElement("Patient");
                    xmlWriter.WriteAttributeString("ID", "SearchPatient-ID");
                    xmlWriter.WriteElementString("LastName", "Search Last");
                    xmlWriter.WriteElementString("FirstName", "Search First");

                    xmlWriter.WriteStartElement("PatientDataAtPresent");

                    xmlWriter.WriteElementString("DateOfBirth", "1956-07-28");
                    xmlWriter.WriteElementString("Gender", "Female");
                    xmlWriter.WriteElementString("Height", "1.82");
                    xmlWriter.WriteElementString("Weight", "64");
                    xmlWriter.WriteElementString("Ethnicity", "Caucasian");
                    xmlWriter.WriteEndElement(); //PatientDataAtPresent

                    xmlWriter.WriteEndElement(); //Patient
                    xmlWriter.WriteEndElement(); //Patients
                    xmlWriter.WriteEndElement();
                    xmlWriter.WriteEndDocument();
                    //                xmlWriter.WriteString(@"
                    //<ndd>
                    //<command>Test xml data</command><Patients>
                    //    <Patient ID=""PSM-11213"">
                    //      <LastName>Smith</LastName>
                    //      <FirstName>Peter</FirstName></Patient>
                    //</Patients>
                    //</ndd>");
                    xmlWriter.Flush();
                    xmlWriter.Close();
                    return(XmlExchangeFile);
                }
                finally
                {
                    xmlWriter.Close();
                }
            }
        }
Ejemplo n.º 30
0
        private static void AddCommand(string strCommand, System.Xml.XmlTextWriter xmlWriter, Dictionary <string, string> cmdParameters)
        {
            xmlWriter.WriteStartElement("Command");
            xmlWriter.WriteAttributeString("Type", strCommand);

            foreach (var cmdParameter in cmdParameters)
            {
                xmlWriter.WriteStartElement("Parameter");
                xmlWriter.WriteAttributeString("Name", cmdParameter.Key);
                xmlWriter.WriteValue(cmdParameter.Value);
                xmlWriter.WriteEndElement();//Param
            }

            xmlWriter.WriteEndElement();//command
        }
Ejemplo n.º 31
0
        private void saveButton_Click(object sender, EventArgs e)
        {
            string settingsFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\DichMusicHelperPathSettings.xml";

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(settingsFile, System.Text.Encoding.Unicode))
            {
                writer.WriteStartElement("PathSettings");
                writer.WriteAttributeString("Path", pathTextBox.Text);
                writer.WriteAttributeString("CreateFolder", createFolderBox.Checked.ToString());
                writer.WriteEndElement();
                writer.Close();
            }

            this.Close();
        }
        private void RebuildMeaningEntry(System.Xml.XmlTextWriter xmlOutput, string topAnalysisWS)
        {
            m_Meaning = "<meaning app=\"" + m_meaningApp + "\" id=\"" + m_meaningId + "\"";
            if (IsRef || MeaningId == "funold")
            {
                m_Meaning += " funcWS=\"";
                if (m_RefFuncWS != string.Empty)
                {
                    m_Meaning += m_RefFuncWS;
                }
                else
                {
                    m_Meaning += topAnalysisWS;
                }
                if (IsRef)
                {
                    m_Meaning += "\" func=\"" + m_RefFunc + "\"";
                }
                else
                {
                    m_Meaning += "\"";
                }
            }
            m_Meaning += "/>";
            if (xmlOutput != null)
            {
                xmlOutput.WriteStartElement("meaning");
                xmlOutput.WriteAttributeString("app", m_meaningApp);
                xmlOutput.WriteAttributeString("id", m_meaningId);
                if (IsRef || MeaningId == "funold")
                {
                    if (m_RefFuncWS != string.Empty)
                    {
                        xmlOutput.WriteAttributeString("funcWS", m_RefFuncWS);
                    }
                    else
                    {
                        xmlOutput.WriteAttributeString("funcWS", topAnalysisWS);
                    }

                    if (IsRef)
                    {
                        xmlOutput.WriteAttributeString("func", m_RefFunc);
                    }
                }
                xmlOutput.WriteEndElement();
            }
        }
Ejemplo n.º 33
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int callstack_uid;

            if (int.TryParse(Request.QueryString["callstack_uid"], out callstack_uid) == false)
                callstack_uid = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Callstack");

                DB.LoadCallstack(callstack_uid,
                    delegate(int depth, string funcname, string fileline)
                    {
                        writer.WriteStartElement("Singlestep");
                        writer.WriteAttributeString("depth", depth.ToString());
                        this.WriteCData(writer, "Funcname", funcname);
                        this.WriteCData(writer, "Fileline", fileline);
                        writer.WriteEndElement();
                    }
                );

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
Ejemplo n.º 34
0
 protected static void WriteParameter(System.Xml.XmlTextWriter xmlWriter, string strFeature, string strValue)
 {
     xmlWriter.WriteStartElement("Parameter");
     xmlWriter.WriteAttributeString("Name", strFeature);
     xmlWriter.WriteValue(strValue);
     xmlWriter.WriteEndElement();//parameter
 }
Ejemplo n.º 35
0
        private void button1_Click(object sender, EventArgs e)
        {
            string settingsFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\DichMusicHelperProxySettings.xml";

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(settingsFile, System.Text.Encoding.Unicode))
            {
                writer.WriteStartElement("ProxySettings");
                writer.WriteAttributeString("Server", serverBox.Text);
                writer.WriteAttributeString("Port", portBox.Text);
                writer.WriteAttributeString("Login", loginBox.Text);
                writer.WriteAttributeString("Password", passwordBox.Text);
                writer.WriteAttributeString("UseProxy", useProxyBox.Checked.ToString());
                writer.WriteEndElement();
                writer.Close();
            }

            this.Close();
        }
Ejemplo n.º 36
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int project_uid;

            if (int.TryParse(Request.QueryString["project"], out project_uid) == false)
                project_uid = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Report");
                writer.WriteAttributeString("project", project_uid.ToString());

                writer.WriteStartElement("Items");

                DB.LoadReportDeleted(project_uid,
                    delegate(int report_uid, string login_id, string ipaddr, DateTime reported_time, string relative_time, int callstack_uid, string funcname, string version, string filename, string assigned, string uservoice, int num_comments)
                    {
                        writer.WriteStartElement("Item");

                        writer.WriteAttributeString("report_uid", report_uid.ToString());
                        writer.WriteAttributeString("login_id", login_id);
                        writer.WriteAttributeString("ipaddr", ipaddr);
                        writer.WriteAttributeString("reported_time", reported_time.ToString());
                        writer.WriteAttributeString("relative_time", relative_time);
                        writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());
                        writer.WriteAttributeString("assigned", assigned);
                        writer.WriteAttributeString("num_comments", num_comments.ToString());
                        this.WriteCData(writer, "Funcname", funcname);
                        this.WriteCData(writer, "Version", version);
                        this.WriteCData(writer, "Filename", filename);
                        this.WriteCData(writer, "Uservoice", uservoice);

                        writer.WriteEndElement();
                    }
                );
                writer.WriteEndElement(); // Items
                writer.WriteEndElement(); // Report
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
Ejemplo n.º 37
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int callstack_uid;

            if (int.TryParse(Request.QueryString["callstack_uid"], out callstack_uid) == false)
                callstack_uid = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Comment");

                writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());

                DB.ForEachCallstackComment CommentWriter = delegate(string author, string comment, DateTime created)
                {
                    writer.WriteStartElement("Item");

                    writer.WriteAttributeString("author", author);
                    writer.WriteAttributeString("created", created.ToString());

                    writer.WriteCData(comment);

                    writer.WriteEndElement();
                };

                DB.LoadCallstackComment(callstack_uid, CommentWriter);

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
Ejemplo n.º 38
0
        public void writeGPX(string filename)
        {
            System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx", Encoding.ASCII);

            xw.WriteStartElement("gpx");
            xw.WriteAttributeString("creator", MainV2.instance.Text);
            xw.WriteAttributeString("xmlns", "http://www.topografix.com/GPX/1/1");

            xw.WriteStartElement("trk");

            xw.WriteStartElement("trkseg");

            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

            foreach (Data mod in flightdata)
            {
                xw.WriteStartElement("trkpt");
                xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("ele", mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("time", mod.datetime.ToString("yyyy-MM-ddTHH:mm:sszzzzzz"));
                xw.WriteElementString("course", (mod.model.Orientation.heading).ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("roll", mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("pitch", mod.model.Orientation.tilt.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("mode", mod.mode);

                //xw.WriteElementString("speed", mod.model.Orientation.);
                //xw.WriteElementString("fix", mod.model.Location.altitude);

                xw.WriteEndElement();
            }


            xw.WriteEndElement(); // trkseg
            xw.WriteEndElement(); // trk

            int a = 0;
            foreach (Data mod in flightdata)
            {
                xw.WriteStartElement("wpt");
                xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("name", (a++).ToString());
                xw.WriteEndElement();//wpt
            }

            xw.WriteEndElement(); // gpx

            xw.Close();
        }
Ejemplo n.º 39
0
		public void Ask(SelectableSource source, TextWriter output) {
			bool result = Ask(source);
			System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter(output);
			w.Formatting = System.Xml.Formatting.Indented;
			w.WriteStartElement("sparql");
			w.WriteAttributeString("xmlns", "http://www.w3.org/2001/sw/DataAccess/rf1/result");
			w.WriteStartElement("head");
			w.WriteEndElement();
			w.WriteStartElement("results");
			w.WriteStartElement("boolean");
			w.WriteString(result ? "true" : "false");
			w.WriteEndElement();
			w.WriteEndElement();
			w.WriteEndElement();
			w.Close();
		}
        private void GenerateEventSchemas(UPnPDevice d, System.IO.DirectoryInfo dirInfo, bool cleanSchema)
        {
            System.IO.MemoryStream ms = new MemoryStream();
            System.Xml.XmlTextWriter X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8);
            X.Formatting = System.Xml.Formatting.Indented;

            foreach(UPnPDevice ed in d.EmbeddedDevices)
            {
                GenerateEventSchemas(ed,dirInfo,cleanSchema);
            }
            foreach(UPnPService s in d.Services)
            {
                Hashtable h = new Hashtable();
                int j=1;

                foreach(string sn in s.GetSchemaNamespaces())
                {
                    h[sn] = "CT"+j.ToString();
                    ++j;
                }
                X.WriteStartDocument();
                X.WriteStartElement("xsd","schema","http://www.w3.org/2001/XMLSchema");
                X.WriteAttributeString("targetNamespace","urn:schemas-upnp-org:event-1-0");
                X.WriteAttributeString("xmlns","upnp",null,"http://www.upnp.org/Schema/DataTypes");
                X.WriteAttributeString("xmlns","urn:schemas-upnp-org:event-1-0");

                foreach(UPnPStateVariable v in s.GetStateVariables())
                {
                    if (v.SendEvent)
                    {
                        X.WriteStartElement("xsd","element",null); // Element1
                        X.WriteAttributeString("name","propertyset");
                        X.WriteAttributeString("type","propertysetType");

                        if (!cleanSchema)
                        {
                            X.WriteComment("Note: Some schema validation tools may consider the following xsd:any element to be ambiguous in its placement");
                            X.WriteStartElement("xsd","any",null);
                            X.WriteAttributeString("namespace","##other");
                            X.WriteAttributeString("minOccurs","0");
                            X.WriteAttributeString("maxOccurs","unbounded");
                            X.WriteAttributeString("processContents","lax");
                            X.WriteEndElement(); //ANY
                        }

                        X.WriteStartElement("xsd","complexType",null);
                        X.WriteAttributeString("name","propertysetType");

                        X.WriteStartElement("xsd","sequence",null);
                        X.WriteStartElement("xsd","element",null); // Element2
                        X.WriteAttributeString("name","property");
                        X.WriteAttributeString("maxOccurs","unbounded");
                        X.WriteStartElement("xsd","complexType",null);
                        X.WriteStartElement("xsd","sequence",null);

                        X.WriteStartElement("xsd","element",null); // Element3
                        X.WriteAttributeString("name",v.Name);
                        if (v.ComplexType==null)
                        {
                            // Simple Type
                            X.WriteStartElement("xsd","complexType",null);
                            X.WriteStartElement("xsd","simpleContent",null);
                            X.WriteStartElement("xsd","extension",null);
                            X.WriteAttributeString("base","upnp:"+v.ValueType);
                            if (!cleanSchema)
                            {
                                X.WriteStartElement("xsd","anyAttribute",null);
                                X.WriteAttributeString("namespace","##other");
                                X.WriteAttributeString("processContents","lax");
                                X.WriteEndElement(); // anyAttribute
                            }
                            X.WriteEndElement(); // extension
                            X.WriteEndElement(); // simpleContent
                            X.WriteEndElement(); // complexType
                        }
                        else
                        {
                            // Complex Type
                            X.WriteAttributeString("type",h[v.ComplexType.Name_NAMESPACE].ToString()+":"+v.ComplexType.Name_LOCAL);
                        }
                        X.WriteEndElement(); // Element3
                        if (!cleanSchema)
                        {
                            X.WriteStartElement("xsd","any",null);
                            X.WriteAttributeString("namespace","##other");
                            X.WriteAttributeString("minOccurs","0");
                            X.WriteAttributeString("maxOccurs","unbounded");
                            X.WriteAttributeString("processContents","lax");
                            X.WriteEndElement(); // any
                        }
                        X.WriteEndElement(); // sequence
                        if (!cleanSchema)
                        {
                            X.WriteStartElement("xsd","anyAttribute",null);
                            X.WriteAttributeString("namespace","##other");
                            X.WriteAttributeString("processContents","lax");
                            X.WriteEndElement(); // anyAttribute
                        }
                        X.WriteEndElement(); // complexType
                        X.WriteEndElement(); // Element2
                        if (!cleanSchema)
                        {
                            X.WriteStartElement("xsd","any",null);
                            X.WriteAttributeString("namespace","##other");
                            X.WriteAttributeString("minOccurs","0");
                            X.WriteAttributeString("maxOccurs","unbounded");
                            X.WriteAttributeString("processContents","lax");
                            X.WriteEndElement(); // any
                        }
                        X.WriteEndElement(); // sequence
                        if (!cleanSchema)
                        {
                            X.WriteStartElement("xsd","anyAttribute",null);
                            X.WriteAttributeString("namespace","##other");
                            X.WriteAttributeString("processContents","lax");
                            X.WriteEndElement(); // anyAttribute
                        }
                        X.WriteEndElement(); // complexType;
                        X.WriteEndElement(); // Element1
                    }
                }

                X.WriteEndElement(); // schema
                X.WriteEndDocument();

                StreamWriter writer3;

                DText PP = new DText();
                PP.ATTRMARK = ":";
                PP[0] = s.ServiceURN;
                writer3 = File.CreateText(dirInfo.FullName + "\\"+PP[PP.DCOUNT()-1]+"_Events.xsd");

                System.Text.UTF8Encoding U = new System.Text.UTF8Encoding();
                X.Flush();
                ms.Flush();
                writer3.Write(U.GetString(ms.ToArray(),2,ms.ToArray().Length-2));
                writer3.Close();
                ms = new MemoryStream();
                X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8);
                X.Formatting = System.Xml.Formatting.Indented;
            }
        }
Ejemplo n.º 41
0
        //e.g. Worklist, CurveData, Attachment_Type, Attachment_Path
        protected virtual string ReturnSupportedFeatures()
        {
            //<?xml version="1.0" encoding="utf-16"?>
              //<ndd>
              //    <Command Type="SupportedFeatures">
              //        <Parameter Name="SearchPatients"></Parameter>
              //    </Command>
              //</ndd>

              StringBuilder sb = new System.Text.StringBuilder();

              using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(new System.IO.StringWriter(sb, CultureInfo.InvariantCulture)))
              {
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("ndd");
            xmlWriter.WriteStartElement("Command");
            xmlWriter.WriteAttributeString("Type", Commands.SupportedFeatures.Command);

            foreach (string strFeature in GetSupportedFeatures())
            {
              xmlWriter.WriteStartElement("Parameter");
              xmlWriter.WriteAttributeString("Name", strFeature);
              xmlWriter.WriteValue("True");
              xmlWriter.WriteEndElement();//parameter
            }

            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();
            //                xmlWriter.WriteString(@"
            //<ndd>
            //<command>Test xml data</command><Patients>
            //    <Patient ID=""PSM-11213"">
            //      <LastName>Smith</LastName>
            //      <FirstName>Peter</FirstName></Patient>
            //</Patients>
            //</ndd>");
            xmlWriter.Flush();
            xmlWriter.Close();
            return sb.ToString();
              }
        }
Ejemplo n.º 42
0
 public byte[] CreatePlayList(Uri baseuri, IEnumerable<KeyValuePair<string,string>> parameters)
 {
   var queries = String.Join("&", parameters.Select(kv => Uri.EscapeDataString(kv.Key) + "=" + Uri.EscapeDataString(kv.Value)));
   var stream = new System.IO.StringWriter();
   var xml = new System.Xml.XmlTextWriter(stream);
   xml.Formatting = System.Xml.Formatting.Indented;
   xml.WriteStartElement("ASX");
   xml.WriteAttributeString("version", "3.0");
   if (Channels.Count>0) {
     xml.WriteElementString("Title", Channels[0].ChannelInfo.Name);
   }
   foreach (var c in Channels) {
     string name = c.ChannelInfo.Name;
     string contact_url = null;
     if (c.ChannelInfo.URL!=null) {
       contact_url = c.ChannelInfo.URL;
     }
     var stream_url = new UriBuilder(baseuri);
     stream_url.Scheme = "mms";
     if (stream_url.Path[stream_url.Path.Length-1]!='/') {
       stream_url.Path += '/';
     }
     stream_url.Path +=
       c.ChannelID.ToString("N").ToUpper() +
       c.ChannelInfo.ContentExtension;
     if (queries!="") {
       stream_url.Query = queries;
     }
     xml.WriteStartElement("Entry");
     xml.WriteElementString("Title", name);
     if (contact_url!=null && contact_url!="") {
       xml.WriteStartElement("MoreInfo");
       xml.WriteAttributeString("href", contact_url);
       xml.WriteEndElement();
     }
     xml.WriteStartElement("Ref");
     xml.WriteAttributeString("href", stream_url.Uri.ToString());
     xml.WriteEndElement();
     xml.WriteEndElement();
   }
   xml.WriteEndElement();
   xml.Close();
   var res = stream.ToString();
   try {
     return System.Text.Encoding.GetEncoding(932).GetBytes(res);
   }
   catch (System.Text.EncoderFallbackException) {
     return System.Text.Encoding.UTF8.GetBytes(res);
   }
 }
Ejemplo n.º 43
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int project_uid;
            int pageNo;
            int pageSize;
            bool seperate_version;
            string specific_version;
            int hideResolved = 0;
            int fromDate;
            int toDate;

            if (int.TryParse(Request.QueryString["project"], out project_uid) == false)
                project_uid = 1;

            if (int.TryParse(Request.QueryString["pageNo"], out pageNo) == false)
                pageNo = 1;

            if (int.TryParse(Request.QueryString["pageSize"], out pageSize) == false)
                pageSize = 30;

            if (int.TryParse(Request.QueryString["from"], out fromDate) == false)
                fromDate = 0;

            if (int.TryParse(Request.QueryString["to"], out toDate) == false)
                toDate = 0;

            if (bool.TryParse(Request.QueryString["sv"], out seperate_version) == false)
                seperate_version = false;

            specific_version = Request.QueryString["ver"];
            if (specific_version != null)
            {
                specific_version.Trim();
                if (specific_version.Length <= 0)
                    specific_version = null;
            }

            string temp1 = Request.QueryString["hideResolved"];
            string temp2 = Request.QueryString["hideExamination"];
            Boolean check1 = false;
            Boolean check2 = false;
            if (temp1 != null)
                check1 = Boolean.Parse(temp1);
            if (temp2 != null)
                check2 = Boolean.Parse(temp2);
            if (check1 && check2)
                hideResolved = 3;
            else if (check1)
                hideResolved = 1;
            else if (check2)
                hideResolved = 2;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Callstack");
                writer.WriteAttributeString("project", project_uid.ToString());
                writer.WriteAttributeString("pageNo", pageNo.ToString());
                writer.WriteAttributeString("pageSize", pageSize.ToString());
                writer.WriteAttributeString("req", specific_version);

                writer.WriteStartElement("Items");

                DB.ForEachCallstackGroup ItemWriter = delegate(int count, int callstack_uid, string funcname, string version, DateTime latest_time, string relative_time, string assigned, int num_comments)
                {
                    writer.WriteStartElement("Item");

                    writer.WriteAttributeString("count", count.ToString());
                    writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());
                    writer.WriteAttributeString("latest_time", latest_time.ToString());
                    writer.WriteAttributeString("relative_time", relative_time);
                    writer.WriteAttributeString("assigned", assigned);
                    writer.WriteAttributeString("num_comments", num_comments.ToString());

                    this.WriteCData(writer, "Funcname", funcname);
                    this.WriteCData(writer, "Version", version);

                    writer.WriteEndElement();
                };

                int totalPageSize = 0;
                DB.LoadCallstackList(project_uid, pageNo, pageSize, fromDate, toDate, seperate_version, specific_version, hideResolved, ItemWriter, out totalPageSize);

                writer.WriteEndElement(); // Items

                writer.WriteStartElement("Outputs");
                this.WriteCData(writer, "TotalPageSize", totalPageSize.ToString());
                writer.WriteEndElement(); // Outputs

                writer.WriteEndElement(); // Callstack
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
        public void Output(IList<ValidationResult> list)
        {
            using (System.Xml.XmlTextWriter output = new System.Xml.XmlTextWriter("output.html", Encoding.Unicode))
            {
                output.WriteRaw("<html><head><title>results</title><style type=\"text/css\">.failedcount-0 { display: none; }</style></head><body>");
                output.WriteStartElement("h1");
                output.WriteRaw("Validation Results");
                output.WriteEndElement();

                output.WriteStartElement("h2");
                output.WriteRaw("Summary");
                output.WriteEndElement();

                output.WriteStartElement("ul");
                output.WriteAttributeString("class", "summary");
                foreach (var s in Enum.GetNames(typeof(XCRI.Validation.ContentValidation.ValidationStatus))
                    .Where(vg => vg.ToLower() != "unknown" && vg.ToLower() != "passed")
                    .Reverse())
                {
                    output.WriteStartElement("li");
                    output.WriteAttributeString("class", s.ToString().ToLower());
                    output.WriteRaw(String.Format("{0} ({1})", s, GetCount(list, s)));

                    var vgList = list
                        .Select(vr => vr.ValidationGroup)
                        .Distinct()
                        .OrderBy(vg => vg);

                    if (list.Where(vr => vr.Status.ToString() == s).Sum(x => x.FailedCount) > 0)
                    {

                        output.WriteStartElement("ul");

                        foreach (var vg in vgList)
                        {
                            var filteredModel = list.Where(vr => vr.ValidationGroup == vg).Where(vr => vr.Status.ToString() == s);
                            var filteredCount = filteredModel.Count();
                            if (filteredCount == 0)
                                continue;
                            output.WriteStartElement("li");
                            output.WriteRaw(String.Format("{0} {1} {2}", filteredModel.Count(), vg.ToLower(), (filteredCount == 1 ? s.ToLower() : s.ToLower() + "s")));
                            output.WriteEndElement(); // li
                        }

                        output.WriteEndElement(); // ul

                    }

                    output.WriteEndElement(); // li
                }
                output.WriteEndElement(); // ul

                output.WriteStartElement("h2");
                output.WriteRaw("Details");
                output.WriteEndElement();

                foreach (var s in Enum.GetNames(typeof(XCRI.Validation.ContentValidation.ValidationStatus))
                    .Where(vg => vg.ToLower() != "unknown"))
                {

                    if (list.Where(vr => vr.Status == (XCRI.Validation.ContentValidation.ValidationStatus)Enum.Parse(typeof(XCRI.Validation.ContentValidation.ValidationStatus), s)).Sum(x => x.FailedCount) == 0)
                        continue;

                    output.WriteStartElement("h3");
                    output.WriteRaw(s);
                    output.WriteEndElement();

                    foreach (var vg in list
                        .Select(vr => vr.ValidationGroup)
                    .Distinct())
                    {
                        var filteredModel = list
                            //.Where(vr => vr.FailedCount > 0)
                                .Where(vr => vr.ValidationGroup == vg && vr.Status == (XCRI.Validation.ContentValidation.ValidationStatus)Enum.Parse(typeof(XCRI.Validation.ContentValidation.ValidationStatus), s))
                                .OrderByDescending(vr => vr.Status);
                        var filteredCount = filteredModel.Count();
                        if (filteredCount == 0)
                            continue;

                        output.WriteStartElement("div");
                        output.WriteAttributeString("class", "failedcount-" + filteredModel.Sum(vr => vr.FailedCount).ToString());

                        output.WriteStartElement("h4");
                        output.WriteRaw(vg);
                        output.WriteEndElement();

                        output.WriteStartElement("ul");

                        foreach (var vr in filteredModel)
                        {

                            output.WriteStartElement("div");
                            output.WriteAttributeString("class", "failedcount-" + vr.FailedCount.ToString());

                            output.WriteStartElement("p");
                            output.WriteRaw(String.Format("{0} ({1} failed instance{2})", vr.Message, vr.FailedCount, (vr.FailedCount == 1 ? String.Empty : "s")));
                            output.WriteEndElement();

                            output.WriteRaw("<table cellspacing=\"0\"><thead><tr><th class=\"status\">Status</th><th class=\"numeric\">Line Number</th><th class=\"numeric\">Line Position</th><th>Details</th></tr></thead><tbody>");

                            foreach (var vi in vr.FailedInstances
                                            .OrderBy(vi => vi.LineNumber)
                                            .ThenBy(vi => vi.LinePosition))
                            {

                                output.WriteStartElement("tr");
                                output.WriteAttributeString("class", vi.Status.ToString().ToLower());

                                output.WriteRaw("<td class=\"status\">" + vi.Status.ToString() + "</td>");
                                output.WriteRaw("<td class=\"numeric\">" + (vi.LineNumber.HasValue ? vi.LineNumber.Value.ToString() : "N/A") + "</td>");
                                output.WriteRaw("<td class=\"numeric\">" + (vi.LinePosition.HasValue ? vi.LinePosition.Value.ToString() : "N/A") + "</td>");
                                output.WriteRaw("<td class=\"details\">" + (String.IsNullOrEmpty(vi.Details) ? "N/A" : vi.Details) + "</td>");

                                output.WriteEndElement();

                            }
                            output.WriteRaw("</tbody></table>");

                            output.WriteEndElement();

                        }

                        output.WriteEndElement();

                        output.WriteEndElement();

                    }
                }

                output.WriteRaw("</body></html>");
                output.Flush();
                output.Close();
            }
        }
        public void WriteUserSetting(string SectionName, string EntryName, string EntryValue)
        {
            //  Make sure all of the necessary information was passed to this routine before attempting to write to
              //  the Settings File.
              if (SectionName == null || SectionName == "" || EntryName == null || EntryName == "" || EntryValue == "")
              {
            //  Exit the Method.
            return;
              }

              try
              {
            // If the value is null, remove the entry
            if (EntryValue == null)
            {
              RemoveUserSetting(SectionName, EntryValue);
              return;
            }

            //  Verify that the file is available for reading and that the XML Section and Entry Name values are valid.
            VerifyNotReadOnly();
            string section = SectionName;
            VerifyAndAdjustSection(ref section);
            string entry = EntryName;
            VerifyAndAdjustEntry(ref entry);

            //  If the File does not exist, create it.
            if (System.IO.File.Exists(_filePath))
            {
              System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(_filePath, System.Text.Encoding.UTF8);
              writer.Formatting = System.Xml.Formatting.Indented;
              writer.WriteStartDocument();
              writer.WriteStartElement("profile");
              writer.WriteStartElement("section");
              writer.WriteAttributeString("name", null, section);
              writer.WriteStartElement("entry");
              writer.WriteAttributeString("name", null, entry);
              writer.WriteString(EntryValue);
              writer.WriteEndElement();
              writer.WriteEndElement();
              writer.WriteEndElement();
              writer.Close();

              //  Exit the method now that the file has been created.
              return;

            }

            // The file exists, edit it
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(_filePath);
            System.Xml.XmlElement root = doc.DocumentElement;

            // Get the section element and add it if it's not there
            System.Xml.XmlNode sectionNode = root.SelectSingleNode(GetSectionsPath(section));
            if (sectionNode == null)
            {
              System.Xml.XmlElement element = doc.CreateElement("section");
              System.Xml.XmlAttribute attribute = doc.CreateAttribute("name");
              attribute.Value = section;
              element.Attributes.Append(attribute);
              sectionNode = root.AppendChild(element);
            }

            // Get the entry element and add it if it's not there
            System.Xml.XmlNode entryNode = sectionNode.SelectSingleNode(GetEntryPath(entry));
            if (entryNode == null)
            {
              System.Xml.XmlElement element = doc.CreateElement("entry");
              System.Xml.XmlAttribute attribute = doc.CreateAttribute("name");
              attribute.Value = entry;
              element.Attributes.Append(attribute);
              entryNode = sectionNode.AppendChild(element);
            }

            // Add the value and save the file
            entryNode.InnerText = EntryValue;
            doc.Save(_filePath);

              }
              catch
              {
            //  Exit this Method.
            return;
              }
        }
Ejemplo n.º 46
0
 public void Ask(SelectableSource source, TextWriter output)
 {
     bool result = Ask(source);
     if (MimeType == SparqlXmlQuerySink.MimeType || MimeType == "text/xml") {
         System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter(output);
         w.Formatting = System.Xml.Formatting.Indented;
         w.WriteStartElement("sparql");
         w.WriteAttributeString("xmlns", "http://www.w3.org/2001/sw/DataAccess/rf1/result");
         w.WriteStartElement("head");
         w.WriteEndElement();
         w.WriteStartElement("boolean");
         w.WriteString(result ? "true" : "false");
         w.WriteEndElement();
         w.WriteEndElement();
         w.Flush();
     } else if (MimeType == "text/plain") {
         output.WriteLine(result ? "true" : "false");
     } else {
     }
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Create RSSRoot and write it to stream.
        /// </summary>
        /// <param name="rSSRoot"></param>
        /// <returns></returns>
        public static bool PublishRSS(RSSRoot rSSRoot)
        {
            bool blnResult = true;

            if(rSSRoot == null)
                return(false);

            if(rSSRoot.Channel == null)
                return(false);

            System.Xml.XmlTextWriter oXmlTextWriter = new System.Xml.XmlTextWriter(rSSRoot.OutputStream, System.Text.Encoding.UTF8);

            oXmlTextWriter.WriteStartDocument();

            oXmlTextWriter.WriteStartElement("rss");
            oXmlTextWriter.WriteAttributeString("version", "2.0");

            oXmlTextWriter.WriteStartElement("channel");

            oXmlTextWriter.WriteElementString("link", rSSRoot.Channel.Link);
            oXmlTextWriter.WriteElementString("title", rSSRoot.Channel.Title);
            oXmlTextWriter.WriteElementString("description", rSSRoot.Channel.Description);

            if(rSSRoot.Channel.Docs != "")
                oXmlTextWriter.WriteElementString("docs", rSSRoot.Channel.Docs);

            if(rSSRoot.Channel.PubDate != "")
            {
                System.DateTime sDateTime = System.Convert.ToDateTime(rSSRoot.Channel.PubDate);
                oXmlTextWriter.WriteElementString("pubDate", sDateTime.ToString("ddd, dd MMM yyyy HH:mm:ss G\\MT"));
            }

            if(rSSRoot.Channel.Generator != "")
                oXmlTextWriter.WriteElementString("generator", rSSRoot.Channel.Generator);

            if(rSSRoot.Channel.WebMaster != "")
                oXmlTextWriter.WriteElementString("webMaster", rSSRoot.Channel.WebMaster);

            if(rSSRoot.Channel.Copyright != "")
                oXmlTextWriter.WriteElementString("copyright", rSSRoot.Channel.Copyright);

            if(rSSRoot.Channel.LastBuildDate != "")
            {
                System.DateTime sDateTime = System.Convert.ToDateTime(rSSRoot.Channel.LastBuildDate);
                oXmlTextWriter.WriteElementString("lastBuildDate", sDateTime.ToString("ddd, dd MMM yyyy HH:mm:ss G\\MT"));
            }

            if(rSSRoot.Channel.ManagingEditor != "")
                oXmlTextWriter.WriteElementString("managingEditor", rSSRoot.Channel.ManagingEditor);

            oXmlTextWriter.WriteElementString("language", rSSRoot.Channel.Language.ToString().Replace("_", "-"));

            if(rSSRoot.Image != null)
            {
                oXmlTextWriter.WriteStartElement("image");

                oXmlTextWriter.WriteElementString("url", rSSRoot.Image.URL);
                oXmlTextWriter.WriteElementString("link", rSSRoot.Image.Link);
                oXmlTextWriter.WriteElementString("title", rSSRoot.Image.Title);

                if(rSSRoot.Image.Description != "")
                    oXmlTextWriter.WriteElementString("description", rSSRoot.Image.Description);

                if(rSSRoot.Image.Width != 0)
                    oXmlTextWriter.WriteElementString("width", rSSRoot.Image.Width.ToString());

                if(rSSRoot.Image.Height != 0)
                    oXmlTextWriter.WriteElementString("height", rSSRoot.Image.Height.ToString());

                oXmlTextWriter.WriteEndElement();
            }

            foreach(RSSItem itmCurrent in rSSRoot.Items)
            {
                oXmlTextWriter.WriteStartElement("item");

                if(itmCurrent.Link != "")
                    oXmlTextWriter.WriteElementString("link", itmCurrent.Link);

                if(itmCurrent.Title != "")
                    oXmlTextWriter.WriteElementString("title", itmCurrent.Title);

                if(itmCurrent.Author != "")
                    oXmlTextWriter.WriteElementString("author", itmCurrent.Author);

                if(itmCurrent.PubDate != "")
                {
                    System.DateTime sDateTime = System.Convert.ToDateTime(itmCurrent.PubDate);
                    oXmlTextWriter.WriteElementString("pubDate", sDateTime.ToString("ddd, dd MMM yyyy HH:mm:ss G\\MT"));
                }

                if(itmCurrent.Comment != "")
                    oXmlTextWriter.WriteElementString("comment", itmCurrent.Comment);

                if(itmCurrent.Description != "")
                    oXmlTextWriter.WriteElementString("description", itmCurrent.Description);

                oXmlTextWriter.WriteEndElement();
            }

            oXmlTextWriter.WriteEndElement();
            oXmlTextWriter.WriteEndElement();

            oXmlTextWriter.WriteEndDocument();

            oXmlTextWriter.Flush();
            oXmlTextWriter.Close();

            return(blnResult);
        }
Ejemplo n.º 48
0
		public void Convert(string SfmFileName, string MappingFileName, string OutputFileName,
							string vernWs, string regWs, string natWs)
		{
			m_NumElements = 0;
			// Log.Open(LogFileName);
			if (!UseFiles(SfmFileName, MappingFileName, OutputFileName))
			{
				return;
			}

			using (System.Xml.XmlTextWriter xmlOutput = new System.Xml.XmlTextWriter(m_OutputFileName, System.Text.Encoding.UTF8))
			{
				xmlOutput.Formatting = System.Xml.Formatting.Indented;
				xmlOutput.Indentation = 2;

				WriteOutputFileComment(SfmFileName, MappingFileName, OutputFileName, xmlOutput);

				xmlOutput.WriteComment(" database is the root element for this file ");
				xmlOutput.WriteStartElement("database");

				System.Xml.XmlDocument xmlMap = new System.Xml.XmlDocument();
				try
				{
					xmlMap.Load(m_MappingFileName);
				}
				catch (System.Xml.XmlException e)
				{
					string ErrMsg = String.Format(Sfm2XmlStrings.InvalidMappingFile0_1, m_MappingFileName, e.Message);
					Log.AddError(ErrMsg);
					// put out the warnings and errors
					Log.FlushTo(xmlOutput);
					xmlOutput.WriteEndElement(); // Close the Database node
					xmlOutput.Close();
					return;
				}

				ReadLanguages(xmlMap);

				// === Process the command line args relating to languages ===
				// National ws
				if (natWs.ToLowerInvariant() == STATICS.Ignore)
					IgnoreWs("nat");
				else if (natWs.ToLowerInvariant() == "no-convert")
					NoConvertWs("nat");
				else if (natWs.Length > 0)
					ConvertWs("nat", natWs);

				// Regional ws
				if (regWs.ToLowerInvariant() == STATICS.Ignore)
					IgnoreWs("reg");
				else if (regWs.ToLowerInvariant() == "no-convert")
					NoConvertWs("reg");
				else if (regWs.Length > 0)
					ConvertWs("reg", regWs);

				// Vern ws
	//			if (vernWs.ToLowerInvariant() == "ignore")
	//				IgnoreWs("vern");
				if (vernWs.ToLowerInvariant() == "no-convert")
					NoConvertWs("vern");
				else if (vernWs.Length > 0)
					ConvertWs("vern", vernWs);

				try
				{
					ReadHierarchy(xmlMap);
					ReadAndOutputSettings(xmlMap, xmlOutput);

					// read the mapping file and build internal classes / objects and
					// add field descriptions to output file
					ReadFieldDescriptions(xmlMap);	//  ReadAndOutputFieldDescriptions(xmlMap, xmlOutput);
					ReadCustomFieldDescriptions(xmlMap);

					// read the mapping file inline markers
					ReadInFieldMarkers(xmlMap);

					// Now vaildate the data read in. This must be done in the follwoing order:
					// Languages, Field Descriptions, Hierarchy. Infield Markers must be validated
					// after Languages. This order is needed because the later checks rely on
					// success of the earlier ones.
					ValidateLanguages();	// throw if bad language data
					ValidateFieldDescriptions();
					ValidateCustomFieldDescriptions();
					ValidateHierarchy();
					ValidateInfieldMarkers();
				}
				catch (System.Exception e)
				{
					string ErrMsg = String.Format(Sfm2XmlStrings.UnhandledException0, e.Message);
					Log.AddError(ErrMsg);
				}

				string nl = System.Environment.NewLine;
				string comments = nl;
				comments += " ================================================================" + nl;
				comments += " Element: " + m_Root.Name + nl;
				comments += "  This element contains the inputfile in an XML format." + nl;
				comments += " ================================================================" + nl;
				xmlOutput.WriteComment(comments);
	//			xmlOutput.WriteComment(" This element contains the inputfile in an XML format ");

				try
				{
					//			xmlOutput.WriteStartElement(m_Root.Name);
					//			ProcessSfmFile(xmlOutput);
					ProcessSfmFileNewLogic(xmlOutput);
				}
				catch (System.Exception e)
				{
					string ErrMsg = String.Format(Sfm2XmlStrings.UnhandledException0, e.Message);
					Log.AddError(ErrMsg);
				}
#if false
				if (m_autoFieldsUsed.Count > 0)
				{
					xmlOutput.WriteComment(" This is where the autofield info goes after the data has been processed. ");
					xmlOutput.WriteStartElement("autofields");
					foreach(DictionaryEntry autoEntry in m_autoFieldsUsed)
					{
						AutoFieldInfo afi = autoEntry.Value as AutoFieldInfo;
						xmlOutput.WriteStartElement("field");
						xmlOutput.WriteAttributeString("class", afi.className);
						xmlOutput.WriteAttributeString("sfm", afi.sfmName);
						xmlOutput.WriteAttributeString("fwid", afi.fwDest);
						xmlOutput.WriteEndElement();
					}
					xmlOutput.WriteEndElement();
				}
#endif
				// put out the field descriptions with the autofield info integrated in: for xslt processing...
				comments = nl;
				comments += " ================================================================" + nl;
				comments += " Element: fieldDescriptions" + nl;
				comments += "  This element is put out after the data so that auto fields can be" + nl;
				comments += "  added here.  Otherwise, we'd have to make two passes over the data." + nl;
				comments += "  The additional information related to auto fields is used in the" + nl;
				comments += "  XSLT processing for building the phase2 output file." + nl;
				comments += " ================================================================" + nl;
				xmlOutput.WriteComment(comments);

				xmlOutput.WriteStartElement("fieldDescriptions");
				foreach(DictionaryEntry fieldEntry in m_FieldDescriptionsTable)
				{
					ClsFieldDescription fd = fieldEntry.Value as ClsFieldDescription;
					if (fd is ClsCustomFieldDescription)
						continue;	// the custom fields will be put out in a CustomFields section following...

					if (m_autoFieldsBySFM.ContainsKey(fd.SFM))
					{
						ArrayList afiBysfm = m_autoFieldsBySFM[fd.SFM] as ArrayList;
						foreach(AutoFieldInfo afi in afiBysfm)
						{
							fd.AddAutoFieldInfo(afi.className, afi.fwDest);
						}
					}
					fd.ToXmlLangString(xmlOutput);
	//				string xmldata = fd.ToXmlLangString(xmlOutput);
					// xmlOutput.WriteRaw(xmldata);
				}
				xmlOutput.WriteEndElement();

				// put out the field descriptions with the autofield info integrated in: for xslt processing...
				comments = nl;
				comments += " ================================================================" + nl;
				comments += " Element: CustomFieldDescriptions" + nl;
				comments += " ================================================================" + nl;
				xmlOutput.WriteComment(comments);

				xmlOutput.WriteStartElement("CustomFieldDescriptions");
				foreach (DictionaryEntry fieldEntry in m_FieldDescriptionsTable)
				{
					ClsCustomFieldDescription fd = fieldEntry.Value as ClsCustomFieldDescription;
					if (fd == null)
						continue;	// not a custom field

					fd.ToXmlLangString(xmlOutput);
	//				string xmldata = fd.ToXmlLangString(xmlOutput);
					// xmlOutput.WriteRaw(xmldata);
				}
				xmlOutput.WriteEndElement();

				// put out the infield descriptions for xslt processing...
				comments = nl;
				comments += " ================================================================" + nl;
				comments += " Element: inFieldMarkers" + nl;
				comments += "  This is where the infield / inline markers are put out." + nl;
				comments += " ================================================================" + nl;
				xmlOutput.WriteComment(comments);

				OutputInFieldMarkers(xmlOutput);

#if false

				<!-- This is where the autofield information goes.  Needed to make sense
					-- of the field and Records elements that use autofields -->
				<autofields>
					<field class="Entry" sfm="dan" fwid="eires"/>
Ejemplo n.º 49
0
		public static void OutputFunctionNames(bool compact, string k_test_results_path, string file_name, string[] script_functions)
		{
			using (var t = new System.Xml.XmlTextWriter(System.IO.Path.Combine(k_test_results_path, file_name), System.Text.Encoding.ASCII))
			{
				t.Indentation = 1;
				t.IndentChar = '\t';
				t.Formatting = System.Xml.Formatting.Indented;

				t.WriteStartDocument();
				t.WriteStartElement("Functions");
				for (int x = 0; x < script_functions.Length; x++)
				{
					if (script_functions[x] != "123")
					{
						t.WriteStartElement("entry");
						t.WriteAttributeString("key", "0x" + x.ToString("X3"));
						t.WriteAttributeString("value", script_functions[x]);
						t.WriteEndElement();
					}
					else if (!compact)
					{
						t.WriteStartElement("entry");
						t.WriteAttributeString("key", "0x" + x.ToString("X3"));
						t.WriteAttributeString("value", "UNKNOWN");
						t.WriteEndElement();
					}
				}
				t.WriteEndElement();
				t.WriteEndDocument();
			}
		}
Ejemplo n.º 50
0
		public void Export(GridVirtual grid)
		{
			System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Stream, 
				System.Text.Encoding.UTF8);
			
			//write HTML and BODY
			if ( (Mode & ExportHTMLMode.HTMLAndBody) == ExportHTMLMode.HTMLAndBody)
			{
				writer.WriteStartElement("html");
				writer.WriteStartElement("body");
			}

			writer.WriteStartElement("table");

			writer.WriteAttributeString("cellspacing","0");
			writer.WriteAttributeString("cellpadding","0");

			for (int r = 0; r < grid.Rows.Count; r++)
			{
				writer.WriteStartElement("tr");

				for (int c = 0; c < grid.Columns.Count; c++)
				{
					Cells.ICellVirtual cell = grid.GetCell(r,c);
					Position pos = new Position(r,c);
					CellContext context = new CellContext(grid, pos, cell);
					ExportHTMLCell(context, writer);
				}

				//tr
				writer.WriteEndElement();
			}

			//table
			writer.WriteEndElement();

			//write end HTML and BODY
			if ( (Mode & ExportHTMLMode.HTMLAndBody) == ExportHTMLMode.HTMLAndBody)
			{
				//body
				writer.WriteEndElement();
				//html
				writer.WriteEndElement();
			}

			writer.Flush();
		}
Ejemplo n.º 51
0
        /// <summary>
        /// Save results to a xml file
        /// </summary>
        /// <param name="path">Fully qualified file path</param>
        /// <history>
        /// [Curtis_Beard]		09/06/2006	Created
        /// </history>
        private void SaveResultsAsXML(string path)
        {
            System.Xml.XmlTextWriter writer = null;

             try
             {
            stbStatus.Text = string.Format(Language.GetGenericText("SaveSaving"), path);

            // Open the file
            writer = new System.Xml.XmlTextWriter(path, System.Text.Encoding.UTF8);
            writer.Formatting = System.Xml.Formatting.Indented;

            writer.WriteStartDocument(true);
            writer.WriteStartElement("astrogrep");
            writer.WriteAttributeString("version", "1.0");

            // write out search options
            writer.WriteStartElement("options");
            writer.WriteElementString("searchPath", __Grep.StartDirectory);
            writer.WriteElementString("fileTypes", __Grep.FileFilter);
            writer.WriteElementString("searchText", __Grep.SearchText);
            writer.WriteElementString("regularExpressions", __Grep.UseRegularExpressions.ToString());
            writer.WriteElementString("caseSensitive", __Grep.UseCaseSensitivity.ToString());
            writer.WriteElementString("wholeWord", __Grep.UseWholeWordMatching.ToString());
            writer.WriteElementString("recurse", __Grep.UseRecursion.ToString());
            writer.WriteElementString("showFileNamesOnly", __Grep.ReturnOnlyFileNames.ToString());
            writer.WriteElementString("negation", __Grep.UseNegation.ToString());
            writer.WriteElementString("lineNumbers", __Grep.IncludeLineNumbers.ToString());
            writer.WriteElementString("contextLines", __Grep.ContextLines.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("search");
            writer.WriteAttributeString("totalfiles", __Grep.Greps.Count.ToString());

            // get total hits
            int totalHits = 0;
            for (int _index = 0; _index < lstFileNames.Items.Count; _index++)
            {
               HitObject _hit = __Grep.RetrieveHitObject(int.Parse(lstFileNames.Items[_index].SubItems[Constants.COLUMN_INDEX_GREP_INDEX].Text));

               // add to total
               totalHits += _hit.HitCount;

               // clear hit object
               _hit = null;
            }
            writer.WriteAttributeString("totalfound", totalHits.ToString());

            for (int _index = 0; _index < lstFileNames.Items.Count; _index++)
            {
               writer.WriteStartElement("item");
               HitObject _hit = __Grep.RetrieveHitObject(int.Parse(lstFileNames.Items[_index].SubItems[Constants.COLUMN_INDEX_GREP_INDEX].Text));

               writer.WriteAttributeString("file", _hit.FilePath);
               writer.WriteAttributeString("total", _hit.HitCount.ToString());

               // write out lines
               for (int _jIndex = 0; _jIndex < _hit.LineCount; _jIndex++)
                  writer.WriteElementString("line", _hit.RetrieveLine(_jIndex));

               // clear hit object
               _hit = null;

               writer.WriteEndElement();
            }

            writer.WriteEndElement();   //search
            writer.WriteEndElement();   //astrogrep
             }
             catch (Exception ex)
             {
            MessageBox.Show(string.Format(Language.GetGenericText("SaveError"), ex.ToString()), Constants.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             finally
             {
            // Close file
            if (writer != null)
            {
               writer.Flush();
               writer.Close();
            }

            stbStatus.Text = Language.GetGenericText("SaveSaved");
             }
        }
Ejemplo n.º 52
0
        static void ExportDataToXmlSql(IModelDoc2 swModel, IEnumerable<DataToExport> dataToExports)
        {
            try
            {
                //var myXml = new System.Xml.XmlTextWriter(@"\\srvkb\SolidWorks Admin\XML\" + swModel.GetTitle() + ".xml", System.Text.Encoding.UTF8);
            //    const string xmlPath = @"\\srvkb\SolidWorks Admin\XML\";
                const string xmlPath = @"C:\Temp\";
                var myXml = new System.Xml.XmlTextWriter(xmlPath + swModel.GetTitle() + ".xml", System.Text.Encoding.UTF8);

                myXml.WriteStartDocument();
                myXml.Formatting = System.Xml.Formatting.Indented;
                myXml.Indentation = 2;

                // создаем элементы
                myXml.WriteStartElement("xml");
                myXml.WriteStartElement("transactions");
                myXml.WriteStartElement("transaction");

                myXml.WriteStartElement("document");

                foreach (var configData in dataToExports)
                {
                    #region XML

                    // Конфигурация
                    myXml.WriteStartElement("configuration");
                    myXml.WriteAttributeString("name", configData.Config);

                    // Материал
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Материал");
                    myXml.WriteAttributeString("value", configData.Материал);
                    myXml.WriteEndElement();

                    // Наименование  -- Из таблицы свойств
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Наименование");
                    myXml.WriteAttributeString("value", configData.Наименование);
                    myXml.WriteEndElement();

                    // Обозначение
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Обозначение");
                    myXml.WriteAttributeString("value", configData.Обозначение);
                    myXml.WriteEndElement();

                    // Площадь покрытия
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Площадь покрытия");
                    myXml.WriteAttributeString("value", configData.ПлощадьПокрытия);
                    myXml.WriteEndElement();

                    // ERP code
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Код_Материала");
                    myXml.WriteAttributeString("value", configData.КодМатериала);
                    myXml.WriteEndElement();

                    // Длина граничной рамки

                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Длина граничной рамки");
                    myXml.WriteAttributeString("value", configData.ДлинаГраничнойРамки);
                    myXml.WriteEndElement();

                    // Ширина граничной рамки
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Ширина граничной рамки");
                    myXml.WriteAttributeString("value", configData.ШиринаГраничнойРамки);
                    myXml.WriteEndElement();

                    // Сгибы
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Сгибы");
                    myXml.WriteAttributeString("value", configData.Сгибы);
                    myXml.WriteEndElement();

                    // Толщина листового металла
                    myXml.WriteStartElement("attribute");
                    myXml.WriteAttributeString("name", "Толщина листового металла");
                    myXml.WriteAttributeString("value", configData.ТолщинаЛистовогоМеталла);
                    myXml.WriteEndElement();

                    myXml.WriteEndElement();  //configuration

                    #endregion

                    #region SQL

                    try
                    {
                        // var sqlConnection = new SqlConnection(Settings.Default.SQLBaseCon);
                        //"Data Source=srvkb;Initial Catalog=SWPlusDB;Persist Security Info=True;User ID=sa;Password=PDMadmin;MultipleActiveResultSets=True");
                        var sqlConnection = new SqlConnection("Data Source=srvkb;Initial Catalog=SWPlusDB;Persist Security Info=True;User ID=sa;Password=PDMadmin;MultipleActiveResultSets=True");
                        sqlConnection.Open();
                        var spcmd = new SqlCommand("UpDateCutList", sqlConnection) { CommandType = CommandType.StoredProcedure };
                        //spcmd.Parameters.Add("@MaterialsID", SqlDbType.Int).Value = КодМатериала;
                        var partNumber = configData.Обозначение;
                        var description = configData.Наименование;
                        var workpieceX = Convert.ToDouble(configData.ДлинаГраничнойРамки.Replace('.', ','));
                        var workpieceY = Convert.ToDouble(configData.ШиринаГраничнойРамки.Replace('.', ','));
                        var bend = Convert.ToInt32(configData.Сгибы);
                        var thickness = Convert.ToDouble(configData.ТолщинаЛистовогоМеталла.Replace('.', ','));
                        var configuration = configData.Config;

                        spcmd.Parameters.Add("@PartNumber", SqlDbType.NVarChar).Value = partNumber;
                        spcmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value = description;
                        if (configData.ДлинаГраничнойРамки == "") { workpieceX = 0; }
                        spcmd.Parameters.Add("@WorkpieceX", SqlDbType.Float).Value = workpieceX;
                        if (configData.ШиринаГраничнойРамки == "") { workpieceY = 0; }
                        spcmd.Parameters.Add("@WorkpieceY", SqlDbType.Float).Value = workpieceY;
                        if (configData.Сгибы == "") { bend = 0; }
                        spcmd.Parameters.Add("@Bend", SqlDbType.Int).Value = bend;
                        if (configData.ТолщинаЛистовогоМеталла == "") { thickness = 0; }
                        spcmd.Parameters.Add("@Thickness", SqlDbType.Float).Value = thickness;
                        spcmd.Parameters.Add("@Configuration", SqlDbType.NVarChar).Value = configuration;
                        //spcmd.Parameters.Add("@version", SqlDbType.Int);
                        spcmd.ExecuteNonQuery();
                        sqlConnection.Close();
                    }
                    catch (Exception)
                    {
                        // Console.WriteLine(e.Message);
                    }

                    #endregion
                }

                //myXml.WriteEndElement();// ' элемент CONFIGURATION
                myXml.WriteEndElement();// ' элемент DOCUMENT
                myXml.WriteEndElement();// ' элемент TRANSACTION
                myXml.WriteEndElement();// ' элемент TRANSACTIONS
                myXml.WriteEndElement();// ' элемент XML
                // заносим данные в myMemoryStream
                myXml.Flush();

            }
            catch (Exception e)
            {
                //  Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 53
0
        private void writeGPX(string filename)
        {
            using (System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx", Encoding.ASCII))
            {

                xw.WriteStartElement("gpx");

                xw.WriteStartElement("trk");

                xw.WriteStartElement("trkseg");

                List<string> items = new List<string>();

                foreach (string photo in photocoords.Keys)
                {
                    items.Add(photo);
                }

                items.Sort();

                foreach (string photo in items)
                {

                    xw.WriteStartElement("trkpt");
                    xw.WriteAttributeString("lat", ((double[])photocoords[photo])[0].ToString(new System.Globalization.CultureInfo("en-US")));
                    xw.WriteAttributeString("lon", ((double[])photocoords[photo])[1].ToString(new System.Globalization.CultureInfo("en-US")));

                    // must stay as above

                    xw.WriteElementString("time", ((DateTime)filedatecache[photo]).ToString("yyyy-MM-ddTHH:mm:ssZ"));

                    xw.WriteElementString("ele", ((double[])photocoords[photo])[2].ToString(new System.Globalization.CultureInfo("en-US")));
                    xw.WriteElementString("course", ((double[])photocoords[photo])[3].ToString(new System.Globalization.CultureInfo("en-US")));

                    xw.WriteElementString("compass", ((double[])photocoords[photo])[3].ToString(new System.Globalization.CultureInfo("en-US")));

                    xw.WriteEndElement();
                }

                xw.WriteEndElement();
                xw.WriteEndElement();
                xw.WriteEndElement();

                xw.Close();
            }
        }
Ejemplo n.º 54
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int callstack_uid;
            short fromDate = 60;
            short toDate = 0;

            if (int.TryParse(Request.QueryString["callstack_uid"], out callstack_uid) == false)
                callstack_uid = 1;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Counts");

                TrendCountList trendCount = new TrendCountList();

                DB.LoadTrendCount(callstack_uid, fromDate, toDate,
                    delegate(string version, string date, int count)
                    {
                        //dailyCountList[date] = count;

                        DailyCountList dcl;
                        if (trendCount.TryGetValue(version, out dcl) == false)
                        {
                            trendCount[version] = new DailyCountList();
                            for (int i = fromDate; i >= toDate; i--)
                            {
                                TimeSpan days = new TimeSpan(i, 0, 0, 0);
                                DateTime saveDate = DateTime.Now.Subtract(days);

                                string simulated_date = string.Format("{0:0000}-{1:00}-{2:00}", saveDate.Year, saveDate.Month, saveDate.Day);

                                trendCount[version][simulated_date] = 0;
                            }
                        }

                        trendCount[version][date] = count;
                    }
                );

                foreach (KeyValuePair<string, DailyCountList> trend in trendCount)
                {
                    writer.WriteStartElement("Version");
                    writer.WriteAttributeString("name", trend.Key.Replace("\0", ""));

                    foreach (KeyValuePair<string, int> v in trend.Value)
                    {
                        writer.WriteStartElement("Count");
                        writer.WriteAttributeString("date", v.Key);
                        writer.WriteAttributeString("count", v.Value.ToString());
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
Ejemplo n.º 55
0
		public void Run()
		{
			geneticfx.Environment env = new geneticfx.Environment( );
			env.StartGeneration+= new geneticfx.Environment.EventHandlerDelegate( this.StartGenerationHandler );
			env.EndGeneration+= new geneticfx.Environment.EventHandlerDelegate( this.EndGenerationHandler );

			geneticfx.Population initial_population = new geneticfx.Population( 50 );

			System.Collections.ArrayList rects = new System.Collections.ArrayList();

			rects.Add( new RECT(0,0,100,100) );
			rects.Add( new RECT(0,0,100,200) );

			rects.Add( new RECT(0,0,200,100) );
			rects.Add( new RECT(0,0,200,200) );
			
			rects.Add( new RECT(0,0,200,100) );
			rects.Add( new RECT(0,0,200,200) );
			
			rects.Add( new RECT(0,0,100,100) );
			rects.Add( new RECT(0,0,100,200) );
			
			rects.Add( new RECT(0,0,100,100) );
			rects.Add( new RECT(0,0,100,200) );
			rects.Add( new RECT(0,0,100,100) );
			rects.Add( new RECT(0,0,100,200) );

			for (int i=0;i<initial_population.Capacity;i++)
			{
				MyChromosome cs = new MyChromosome( rects );
				cs.RandomizeGenes();
				geneticfx.Organism o = new geneticfx.Organism( cs, 0.0F );
				initial_population.AddOrganism(o);
			}

			env.MutationRate = 0.10F;
			int num_generations=10;
			env.SetupForEvolution( initial_population , geneticfx.FitnessDirection.Minimize);

			string fname ="out.svg";
			fname = System.IO.Path.GetFullPath( fname );

			System.Xml.XmlWriter xw = new System.Xml.XmlTextWriter( fname, System.Text.Encoding.UTF8 );
			xw.WriteStartElement("svg");

			int cur_y = 100;
			for (int i=0;i<num_generations;i++)
			{
				env.EvolveNextGeneration();

				geneticfx.Generation generation = env.CurrentGeneration;

				int cur_x = 100;
				for (int generation_index=0;generation_index<generation.population.Size;generation_index++)
				{
					geneticfx.Organism o = generation.population[ generation_index ];
					MyChromosome mcr = (MyChromosome) o.Genes;

					RECT bb = RECTTOOLS.get_bounding_box( mcr.layout_rects );
					xw.WriteStartElement("g");
					xw.WriteAttributeString( "transform", string.Format( "translate({0},{1})", cur_x, cur_y ) );
					for (int icr=0;icr<mcr.Length;icr++)
					{
						RECT r = mcr.layout_rects [icr];
						xw.WriteStartElement("rect");
						xw.WriteAttributeString( "x", r.x0.ToString() );
						xw.WriteAttributeString( "y", r.y0.ToString());
						xw.WriteAttributeString( "width", r.w.ToString());
						xw.WriteAttributeString( "height", r.h.ToString() );
						xw.WriteAttributeString( "opacity", "0.1");
						xw.WriteEndElement();

						xw.WriteStartElement("text");
						xw.WriteAttributeString( "x", "0" );
						xw.WriteAttributeString( "y", "0" );
						string s = string.Format( "Gen{0} / Org{1} / Fit={2}", generation_index,o.ID,o.Fitness );
						xw.WriteString( s );
						xw.WriteEndElement();

					}
					xw.WriteEndElement();
					

					cur_x += (int) (1000 + 100);
				}
				cur_y += (int) (1000 + 100);


				xw.Flush();
			}
			xw.WriteEndElement();
			xw.Flush();
			xw.Close();

		}
Ejemplo n.º 56
0
 public byte[] CreatePlayList(Uri baseuri)
 {
     var stream = new System.IO.StringWriter();
       var xml = new System.Xml.XmlTextWriter(stream);
       xml.Formatting = System.Xml.Formatting.Indented;
       xml.WriteStartElement("ASX");
       xml.WriteAttributeString("version", "3.0");
       if (Channels.Count>0) {
     xml.WriteElementString("Title", Channels[0].ChannelInfo.Name);
       }
       foreach (var c in Channels) {
     string name = c.ChannelInfo.Name;
     string contact_url = null;
     if (c.ChannelInfo.URL!=null) {
       contact_url = c.ChannelInfo.URL;
     }
     var stream_url = new Uri(baseuri, c.ChannelID.ToString("N").ToUpper() + c.ChannelInfo.ContentExtension);
     xml.WriteStartElement("Entry");
     xml.WriteElementString("Title", name);
     if (contact_url!=null && contact_url!="") {
       xml.WriteStartElement("MoreInfo");
       xml.WriteAttributeString("href", contact_url);
       xml.WriteEndElement();
     }
     xml.WriteStartElement("Ref");
     xml.WriteAttributeString("href", stream_url.ToString());
     xml.WriteEndElement();
     xml.WriteEndElement();
       }
       xml.WriteEndElement();
       xml.Close();
       var res = stream.ToString();
       try {
     return System.Text.Encoding.Default.GetBytes(res);
       }
       catch (System.Text.EncoderFallbackException) {
     return System.Text.Encoding.UTF8.GetBytes(res);
       }
 }
        private void GenerateControlSchemas(UPnPDevice d, System.IO.DirectoryInfo dirInfo, bool cleanSchema)
        {
            System.IO.MemoryStream ms = new MemoryStream();
            System.Xml.XmlTextWriter X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8);
            X.Formatting = System.Xml.Formatting.Indented;

            foreach(UPnPDevice ed in d.EmbeddedDevices)
            {
                GenerateControlSchemas(ed,dirInfo,cleanSchema);
            }
            foreach(UPnPService s in d.Services)
            {
                Hashtable h = new Hashtable();
                int j=1;

                foreach(string sn in s.GetSchemaNamespaces())
                {
                    h[sn] = "CT"+j.ToString();
                    ++j;
                }
                X.WriteStartDocument();
                X.WriteStartElement("xsd","schema","http://www.w3.org/2001/XMLSchema");
                X.WriteAttributeString("targetNamespace",s.ServiceURN);
                X.WriteAttributeString("xmlns",s.ServiceURN);
                X.WriteAttributeString("xmlns","upnp",null,"http://www.upnp.org/Schema/DataTypes");
                IDictionaryEnumerator NE = h.GetEnumerator();
                while(NE.MoveNext())
                {
                    X.WriteAttributeString("xmlns",NE.Value.ToString(),null,NE.Key.ToString());
                }

                foreach(UPnPAction a in s.Actions)
                {
                    X.WriteStartElement("xsd","element",null);
                    X.WriteAttributeString("name",a.Name);
                    X.WriteAttributeString("type",a.Name+"Type");
                    X.WriteEndElement();
                    X.WriteStartElement("xsd","element",null);
                    X.WriteAttributeString("name",a.Name+"Response");
                    X.WriteAttributeString("type",a.Name+"ResponseType");
                    X.WriteEndElement();

                    if (!cleanSchema)
                    {
                        X.WriteComment("Note: Some schema validation tools may consider the following xsd:any element ambiguous in this placement");
                        X.WriteStartElement("xsd","any",null);
                        X.WriteAttributeString("namespace","##other");
                        X.WriteAttributeString("minOccurs","0");
                        X.WriteAttributeString("maxOccurs","unbounded");
                        X.WriteAttributeString("processContents","lax");
                        X.WriteEndElement(); // ANY
                    }

                    X.WriteStartElement("xsd","complexType",null);
                    X.WriteAttributeString("name",a.Name+"Type");

                    X.WriteStartElement("xsd","sequence",null);

                    foreach(UPnPArgument arg in a.Arguments)
                    {
                        if (arg.Direction=="in")
                        {
                            X.WriteStartElement("xsd","element",null);
                            X.WriteAttributeString("name",arg.Name);
                            if (arg.RelatedStateVar.ComplexType==null)
                            {
                                // Simple Types
                                X.WriteStartElement("xsd","complexType",null);
                                X.WriteStartElement("xsd","simpleContent",null);
                                X.WriteStartElement("xsd","extension",null);
                                X.WriteAttributeString("base","upnp:"+arg.RelatedStateVar.ValueType);

                                if (!cleanSchema)
                                {
                                    X.WriteStartElement("xsd","anyAttribute",null);
                                    X.WriteAttributeString("namespace","##other");
                                    X.WriteAttributeString("processContents","lax");
                                    X.WriteEndElement(); // anyAttribute
                                }

                                X.WriteEndElement(); // Extension
                                X.WriteEndElement(); // simpleConent
                                X.WriteEndElement(); // complexType
                            }
                            else
                            {
                                // Complex Types
                                X.WriteAttributeString("type",h[arg.RelatedStateVar.ComplexType.Name_NAMESPACE].ToString()+":"+arg.RelatedStateVar.ComplexType.Name_LOCAL);
                            }
                            X.WriteEndElement(); // element
                        }
                    }

                    if (!cleanSchema)
                    {
                        X.WriteStartElement("xsd","any",null);
                        X.WriteAttributeString("namespace","##other");
                        X.WriteAttributeString("minOccurs","0");
                        X.WriteAttributeString("maxOccurs","unbounded");
                        X.WriteAttributeString("processContents","lax");
                        X.WriteEndElement(); // any
                    }

                    X.WriteEndElement(); // sequence

                    if (!cleanSchema)
                    {
                        X.WriteStartElement("xsd","anyAttribute",null);
                        X.WriteAttributeString("namespace","##other");
                        X.WriteAttributeString("processContents","lax");
                        X.WriteEndElement(); // anyAttribute
                    }
                    X.WriteEndElement(); // complexType

                    // ActionResponse
                    X.WriteStartElement("xsd","complexType",null);
                    X.WriteAttributeString("name",a.Name+"ResponseType");
                    X.WriteStartElement("xsd","sequence",null);

                    foreach(UPnPArgument arg in a.Arguments)
                    {
                        if (arg.Direction=="out" || arg.IsReturnValue)
                        {
                            X.WriteStartElement("xsd","element",null);
                            X.WriteAttributeString("name",arg.Name);
                            if (arg.RelatedStateVar.ComplexType==null)
                            {
                                // Simple
                                X.WriteStartElement("xsd","complexType",null);
                                X.WriteStartElement("xsd","simpleContent",null);
                                X.WriteStartElement("xsd","extension",null);
                                X.WriteAttributeString("base","upnp:"+arg.RelatedStateVar.ValueType);
                                if (!cleanSchema)
                                {
                                    X.WriteStartElement("xsd","anyAttribute",null);
                                    X.WriteAttributeString("namespace","##other");
                                    X.WriteAttributeString("processContents","lax");
                                    X.WriteEndElement(); // anyAttribute
                                }
                                X.WriteEndElement(); // extension
                                X.WriteEndElement(); // simpleContent
                                X.WriteEndElement(); // complexType
                            }
                            else
                            {
                                // Complex
                                X.WriteAttributeString("type",h[arg.RelatedStateVar.ComplexType.Name_NAMESPACE].ToString()+":"+arg.RelatedStateVar.ComplexType.Name_LOCAL);
                            }
                            X.WriteEndElement(); // Element
                        }
                    }
                    // After all arguments
                    if (!cleanSchema)
                    {
                        X.WriteStartElement("xsd","any",null);
                        X.WriteAttributeString("namespace","##other");
                        X.WriteAttributeString("minOccurs","0");
                        X.WriteAttributeString("maxOccurs","unbounded");
                        X.WriteAttributeString("processContents","lax");
                        X.WriteEndElement(); // any
                    }
                    X.WriteEndElement(); // sequence
                    if (!cleanSchema)
                    {
                        X.WriteStartElement("xsd","anyAttribute",null);
                        X.WriteAttributeString("namespace","##other");
                        X.WriteAttributeString("processContents","lax");
                        X.WriteEndElement(); // anyAttribute
                    }
                    X.WriteEndElement(); // complexType
                }

                X.WriteEndElement(); //schema
                X.WriteEndDocument();

                StreamWriter writer3;

                DText PP = new DText();
                PP.ATTRMARK = ":";
                PP[0] = s.ServiceURN;
                writer3 = File.CreateText(dirInfo.FullName + "\\"+PP[PP.DCOUNT()-1]+".xsd");

                System.Text.UTF8Encoding U = new System.Text.UTF8Encoding();
                X.Flush();
                ms.Flush();
                writer3.Write(U.GetString(ms.ToArray(),2,ms.ToArray().Length-2));
                writer3.Close();
                ms = new MemoryStream();
                X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8);
                X.Formatting = System.Xml.Formatting.Indented;
            }
        }
Ejemplo n.º 58
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            int project_uid;
            int pageNo;
            int pageSize;

            int filterType;
            string filterValue;

            int hideResolved = 0;

            if (int.TryParse(Request.QueryString["project"], out project_uid) == false)
                project_uid = 1;

            if (int.TryParse(Request.QueryString["pageNo"], out pageNo) == false)
                pageNo = 1;

            if (int.TryParse(Request.QueryString["pageSize"], out pageSize) == false)
                pageSize = 30;

            if (int.TryParse(Request.QueryString["filterType"], out filterType) == false)
                filterType = 0;

            filterValue = Request.QueryString["filterValue"];
            if (filterValue == null)
                filterValue = "";

            string temp1 = Request.QueryString["hideResolved"];
            string temp2 = Request.QueryString["hideExamination"];
            Boolean check1 = false;
            Boolean check2 = false;
            if (temp1 != null)
                check1 =  Boolean.Parse(temp1);
            if (temp2 != null)
                check2 =  Boolean.Parse(temp2);
            if (check1 && check2)
                hideResolved = 3;
            else if (check1)
                hideResolved = 1;
            else if (check2)
                hideResolved = 2;

            using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8))
            {
                writer.WriteStartDocument();

                writer.WriteStartElement("Report");
                writer.WriteAttributeString("project", project_uid.ToString());
                writer.WriteAttributeString("pageNo", pageNo.ToString());
                writer.WriteAttributeString("pageSize", pageSize.ToString());

                writer.WriteStartElement("Items");

                int totalPageSize = 0;
                DB.LoadReport(project_uid, pageNo, pageSize,
                    delegate(int report_uid, string login_id, string ipaddr, DateTime reported_time, string relative_time, int callstack_uid, string funcname, string version, string filename, string assigned, string uservoice, int num_comments)
                    {
                        writer.WriteStartElement("Item");

                        writer.WriteAttributeString("report_uid", report_uid.ToString());
                        writer.WriteAttributeString("login_id", login_id);
                        writer.WriteAttributeString("ipaddr", ipaddr);
                        writer.WriteAttributeString("reported_time", reported_time.ToString());
                        writer.WriteAttributeString("relative_time", relative_time);
                        writer.WriteAttributeString("callstack_uid", callstack_uid.ToString());
                        writer.WriteAttributeString("assigned", assigned);
                        writer.WriteAttributeString("num_comments", num_comments.ToString());
                        this.WriteCData(writer, "Funcname", funcname);
                        this.WriteCData(writer, "Version", version);
                        this.WriteCData(writer, "Filename", filename);
                        this.WriteCData(writer, "Uservoice", uservoice);

                        writer.WriteEndElement();
                    },
                    out totalPageSize,
                    (DB.ReportWhereFilter)filterType,
                    filterValue,
                    hideResolved
                );
                writer.WriteEndElement(); // Items

                writer.WriteStartElement("Outputs");
                this.WriteCData(writer, "TotalPageSize", totalPageSize.ToString());
                writer.WriteEndElement(); // Outputs

                writer.WriteEndElement(); // Report
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
            }
        }
Ejemplo n.º 59
0
        private void writeGPX(string filename)
        {
            System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".gpx",Encoding.ASCII);

            xw.WriteStartElement("gpx");

            xw.WriteStartElement("trk");

            xw.WriteStartElement("trkseg");

            DateTime start = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,0,0,0);

            foreach (Data mod in flightdata)
            {
                xw.WriteStartElement("trkpt");
                xw.WriteAttributeString("lat", mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteAttributeString("lon", mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("ele", mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("time", start.AddMilliseconds(mod.datetime).ToString("yyyy-MM-ddTHH:mm:sszzzzzz"));
                xw.WriteElementString("course", (mod.model.Orientation.heading).ToString(new System.Globalization.CultureInfo("en-US")));

                xw.WriteElementString("roll", mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")));
                xw.WriteElementString("pitch", mod.model.Orientation.tilt.ToString(new System.Globalization.CultureInfo("en-US")));
                //xw.WriteElementString("speed", mod.model.Orientation.);
                //xw.WriteElementString("fix", mod.model.Location.altitude);

                xw.WriteEndElement();
            }

            xw.WriteEndElement();
            xw.WriteEndElement();
            xw.WriteEndElement();

            xw.Close();
        }
Ejemplo n.º 60
0
        /// <summary> Writes the mapping of all mapped classes of the specified assembly in the specified stream. </summary>
        /// <param name="stream">Where the xml is written.</param>
        /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param>
        public virtual void Serialize(System.IO.Stream stream, System.Reflection.Assembly assembly)
        {
            if(stream == null)
                throw new System.ArgumentNullException("stream");
            if(assembly == null)
                throw new System.ArgumentNullException("assembly");

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter( stream, System.Text.Encoding.UTF8 );
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();
            if(WriteDateComment)
                writer.WriteComment( string.Format( "Generated from NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u") ) );
            WriteHibernateMapping(writer, null);

            // Write imports (classes decorated with the [ImportAttribute])
            foreach(System.Type type in assembly.GetTypes())
            {
                object[] imports = type.GetCustomAttributes(typeof(ImportAttribute), false);
                foreach(ImportAttribute import in imports)
                {
                    writer.WriteStartElement("import");
                    if(import.Class != null && import.Class != string.Empty)
                        writer.WriteAttributeString("class", import.Class);
                    else // Assume that it is the current type that must be imported
                        writer.WriteAttributeString("class", HbmWriterHelper.GetNameWithAssembly(type));
                    if(import.Rename != null && import.Rename != string.Empty)
                        writer.WriteAttributeString("rename", import.Rename);
                    writer.WriteEndElement();
                }
            }

            // Write classes and x-subclasses (classes must come first if inherited by "external" subclasses)
            int classCount = 0;
            System.Collections.ArrayList mappedClassesNames = new System.Collections.ArrayList();
            foreach(System.Type type in assembly.GetTypes())
            {
                if( ! IsClass(type) )
                    continue;
                HbmWriter.WriteClass(writer, type);
                mappedClassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type));
                classCount++;
            }

            System.Collections.ArrayList subclasses = new System.Collections.ArrayList();
            System.Collections.Specialized.StringCollection extendedClassesNames = new System.Collections.Specialized.StringCollection();
            foreach(System.Type type in assembly.GetTypes())
            {
                if( ! IsSubclass(type) )
                    continue;
                bool map = true;
                System.Type t = type;
                while( (t=t.DeclaringType) != null )
                    if (IsClass(t) || AreSameSubclass(type, t)) // If a base class is also mapped... (Note: A x-subclass can only contain x-subclasses of the same family)
                    {
                        map = false; // This class's mapping is already included in the mapping of the base class
                        break;
                    }
                if(map)
                {
                    subclasses.Add(type);
                    if( IsSubclass(type, typeof(SubclassAttribute)) )
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(SubclassAttribute), false)[0] as SubclassAttribute).Extends);
                    else if( IsSubclass(type, typeof(JoinedSubclassAttribute)) )
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(JoinedSubclassAttribute), false)[0] as JoinedSubclassAttribute).Extends);
                    else if( IsSubclass(type, typeof(UnionSubclassAttribute)) )
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(UnionSubclassAttribute), false)[0] as UnionSubclassAttribute).Extends);
                }
            }
            classCount += subclasses.Count;
            MapSubclasses(subclasses, extendedClassesNames, mappedClassesNames, writer);

            writer.WriteEndElement(); // </hibernate-mapping>
            writer.WriteEndDocument();
            writer.Flush();

            if(classCount == 0)
                throw new MappingException("The following assembly contains no mapped classes: " + assembly.FullName);
            if( ! Validate )
                return;

            // Validate the generated XML stream
            try
            {
                writer.BaseStream.Position = 0;
                System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(writer.BaseStream);
                System.Xml.XmlValidatingReader vr = new System.Xml.XmlValidatingReader(tr);

                // Open the Schema
                System.IO.Stream schema = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Mapping.Attributes.nhibernate-mapping.xsd");
                vr.Schemas.Add("urn:nhibernate-mapping-2.2", new System.Xml.XmlTextReader(schema));
                vr.ValidationType = System.Xml.ValidationType.Schema;
                vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlValidationHandler);

                _stop = false;
                while(vr.Read() && !_stop) // Read to validate (stop at the first error)
                    ;
            }
            catch(System.Exception ex)
            {
                Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine);
            }
        }