상속: IDisposable
        /// <summary>
        /// Writes all experiment graph attributes.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="flow">The flow.</param>
        public virtual void WriteGraphAttributes(XmlWriter writer, IExperiment flow)
        {
            string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
            System.IO.Directory.CreateDirectory(path);

            PropertyDescriptorCollection propertiesToWrite = TypeDescriptor.GetProperties(flow);
            foreach (PropertyDescriptor property in propertiesToWrite)
            {
                WriteXmlAttribute(writer, property, flow);
            }

            writer.WriteStartElement("References");
            {
                if (flow.References != null)
                {
                    var serializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(PackageSystem.PackageReference), null);
                    foreach (IPackageReference reference in flow.References)
                    {
                        serializer.Serialize(writer, reference);
                    }
                }
            }
            writer.WriteEndElement();

            // Iterate again and write any elements that are pending.  ALL attributes must be done first, or it results in invalid XML
            foreach (PropertyDescriptor property in propertiesToWrite)
            {
                WriteXmlElement(writer, property, flow);
            }
        }
예제 #2
1
		void WritePatchedImport (XmlWriter writer, string newTarget)
		{
			/* If an import redirect exists, add a fake import to the project which will be used only
			   if the original import doesn't exist. That is, the following import:

			   <Import Project = "PathToReplace" />

			   will be converted into:

			   <Import Project = "PathToReplace" Condition = "Exists('PathToReplace')"/>
			   <Import Project = "ReplacementPath" Condition = "!Exists('PathToReplace')" />
			*/

			// Modify the original import by adding a condition, so that this import will be used only
			// if the targets file exists.

			string cond = "Exists('" + target + "')";
			if (!string.IsNullOrEmpty (Condition))
				cond = "( " + Condition + " ) AND " + cond;
			
			writer.WriteStartElement ("Import", MSBuildProject.Schema);
			writer.WriteAttributeString ("Project", target);
			writer.WriteAttributeString ("Condition", cond);

			// Now add the fake import, with a condition so that it will be used only if the original
			// import does not exist.

			cond = "!Exists('" + target + "')";
			if (!string.IsNullOrEmpty (Condition))
				cond = "( " + Condition + " ) AND " + cond;

			writer.WriteStartElement ("Import", MSBuildProject.Schema);
			writer.WriteAttributeString ("Project", MSBuildProjectService.ToMSBuildPath (null, newTarget));
			writer.WriteAttributeString ("Condition", cond);
		}
    /// <summary>
    /// Applies the transformation from the reader to the writer
    /// </summary>
    /// <param name="reader"></param>
    /// <param name="writer"></param>
    public void Transform(XmlReader reader, XmlWriter writer) {
      Contract.Requires(reader != null);
      Contract.Requires(writer != null);

      while (reader.Read())
        this.WriteNodeSingle(reader, writer);
    }
예제 #4
1
        protected internal override void WriteXmlAttributes(XmlWriter writer)
        {
            if (Mode == VerticesEnumeratorMode.Range)
            {
                writer.WriteStartAttribute(StartField);
                writer.WriteValue(Start);
                writer.WriteEndAttribute();

                writer.WriteStartAttribute(EndField);
                writer.WriteValue(End);
                writer.WriteEndAttribute();

                writer.WriteStartAttribute(IncField);
                writer.WriteValue(Increment);
                writer.WriteEndAttribute();
            }
            
            if (Mode != VerticesEnumeratorMode.All)
            {
                writer.WriteStartAttribute(ModeField);
                writer.WriteValue(Mode.ToString());
                writer.WriteEndAttribute();
            }

            base.WriteXmlAttributes(writer);
        }
예제 #5
1
        void SanitizerNodeVisited(string nodeName, HtmlNode node, XmlWriter writer)
        {
            if (nodeName == "img" && node.Attributes["src"] != null && node.Attributes["src"].Value.StartsWith("cid:"))
            {
                // split src
                var src = node.Attributes["src"].Value.Split(new[] { ':' }, 2);

                if (src.Length == 2)
                {
                    // Find inline attachment with given contentid
                    var document = source.Documents.FirstOrDefault(d => d.ContentType == ContentType.Inline && d.ContentId == src[1]);

                    if (document != null)
                    {
                        // Replace content-id url with filename
                        var filename = ClientState.Current.Storage.ResolvePhysicalFilename(".", document.StreamName);

                        node.Attributes["src"].Value = String.Format("file://{0}", filename);
                    }
                }
            }
            else if (nodeName == "a" && node.Attributes["href"] != null)
            {
                var url = node.Attributes["href"].Value;

                // Clean href and inject javascript hook
                node.Attributes["href"].Value = String.Empty;

                writer.WriteAttributeString("onclick", String.Format("javascript:window.external.JsNavigate('{0}')", url));
            }
        }
예제 #6
1
        internal void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("classCode", ClassCode);

            its.TemplateSignpost(templateId + "#" + templateText, writer);
            writeXML(writer);

            if (assignedPerson != null)
            {
                writer.WriteStartElement("assignedPerson");
                assignedPerson.TemplateId = templateId;
                assignedPerson.TemplateText = "assignedPerson";
                assignedPerson.WriteXml(writer);
                writer.WriteEndElement();
            }

            if (assignedDevice != null)
            {
                writer.WriteStartElement("assignedAuthoringDevice");
                assignedDevice.TemplateId = templateId;
                assignedDevice.TemplateText = "assignedAuthoringDevice";
                assignedDevice.WriteXml(writer);
                writer.WriteEndElement();
            }

            if (representedOrganisation != null)
            {
                writer.WriteStartElement("representedOrganization");
                representedOrganisation.TemplateId = templateId;
                representedOrganisation.TemplateText = "representedOrganization";
                representedOrganisation.WriteXml(writer);
                writer.WriteEndElement();
            }
        }
        public override void SerializeNetwork(XmlWriter xmlWriter)
        {
            base.SerializeNetwork(xmlWriter);

            var expander = ControlElements[0] as SliderExpanderDouble;
            if (expander == null) return;

            xmlWriter.WriteStartAttribute("SliderMax");
            xmlWriter.WriteValue(expander.SliderMax);
            xmlWriter.WriteEndAttribute();

            xmlWriter.WriteStartAttribute("SliderMin");
            xmlWriter.WriteValue(expander.SliderMin);
            xmlWriter.WriteEndAttribute();

            xmlWriter.WriteStartAttribute("SliderValue");
            xmlWriter.WriteValue(expander.SliderValue);
            xmlWriter.WriteEndAttribute();

            xmlWriter.WriteStartAttribute("SliderStep");
            xmlWriter.WriteValue(expander.SliderStep);
            xmlWriter.WriteEndAttribute();

            xmlWriter.WriteStartAttribute("IsExpanded");
            xmlWriter.WriteValue(expander.IsExpanded);
            xmlWriter.WriteEndAttribute();
        }
예제 #8
1
 public override void PrintQuery(XmlWriter w) {
     w.WriteStartElement(this.GetType().Name);
     w.WriteAttributeString("op", (isOr ? Operator.Op.OR : Operator.Op.AND).ToString());
     opnd1.PrintQuery(w);
     opnd2.PrintQuery(w);
     w.WriteEndElement();
 }
예제 #9
1
 // Methods
 internal virtual void WriteTo( XmlWriter xmlWriter )
 {
     xmlWriter.WriteStartElement( XmlDiff.Prefix, "descriptor", XmlDiff.NamespaceUri );
     xmlWriter.WriteAttributeString( "opid", _operationID.ToString() );
     xmlWriter.WriteAttributeString( "type", Type );
     xmlWriter.WriteEndElement();
 }
 void IXmlSerializable.WriteXml(XmlWriter writer)
 {
     if (address != null)
     {
         address.WriteContentsTo(this.addressVersion, writer);
     }
 }
예제 #11
1
        private static void WriteCLPSToXML(XmlWriter writer)
        {
            writer.WriteStartElement("CLPS");

            uint clps_addr = m_Overlay.ReadPointer(0x60);
            uint clps_num = m_Overlay.Read16(clps_addr + 0x06);
            uint clps_size = (uint)(8 + (clps_num * 8));
            byte[][] entries = new byte[clps_num][];
            uint entry = clps_addr + 0x08;

            for (int i = 0; i < clps_num; i++)
            {
                entries[i] = new byte[8];

                for (int j = 0; j < 8; j++)
                    entries[i][j] = m_Overlay.Read8((uint)(entry + (j)));

                entry += 8;
            }

            for (int i = 0; i < entries.Length; i++)
            {
                writer.WriteStartElement("Entry");
                writer.WriteStartElement("Value");
                for (int j = 0; j < entries[i].Length; j++)
                    writer.WriteElementString("Byte", entries[i][j].ToString());

                writer.WriteEndElement();
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
            internal override void WriteTo(XmlWriter xml)
            {
                if (xml == null)
                    return;

                xml.WriteComment(SR.GetString(SR.ServiceNameFromClient));
                xml.WriteElementString("ServiceName", this.serviceBindingNameSentByClient);

                xml.WriteComment(SR.GetString(SR.ServiceNameOnService));
                xml.WriteStartElement("ServiceNameCollection");
                if (this.serviceNameCollectionConfiguredOnServer == null || this.serviceNameCollectionConfiguredOnServer.Count < 1)
                {
                    xml.WriteElementString("ServiceName", this.defaultServiceBindingNameOfServer);
                }
                else
                {
                    foreach (string serviceName in this.serviceNameCollectionConfiguredOnServer)
                    {
                        xml.WriteElementString("ServiceName", serviceName);
                    }
                }

                xml.WriteFullEndElement();

            }
예제 #13
1
 public static void writeVertex(XmlWriter writer, Vector2D vert)
 {
     writer.WriteStartElement("vertex");
     writer.WriteAttributeString("x", vert.x.ToString());
     writer.WriteAttributeString("y", vert.y.ToString());
     writer.WriteEndElement();
 }
예제 #14
1
 private static void WriteAlbum(XmlWriter writer, string albumTitle, string artist)
 {
     writer.WriteStartElement("album");
     writer.WriteElementString("title", albumTitle);
     writer.WriteElementString("artist", artist);
     writer.WriteEndElement();
 }
예제 #15
1
        public override void Validate(XmlWriter output, SchematronRuntimeOptions options)
        {
            if (output == null) throw new ArgumentNullException("output");
             if (options == null) throw new ArgumentNullException("options");

             this.executable.Run(output, GetXsltOptions(options));
        }
예제 #16
1
		internal WrappedSerializer(Serialization.DataFormat dataFormat, string streamName, TextWriter output) : base(dataFormat, streamName)
		{
			this.firstCall = true;
			this.textWriter = output;
			Serialization.DataFormat dataFormat1 = this.format;
			switch (dataFormat1)
			{
				case Serialization.DataFormat.Text:
				{
					return;
				}
				case Serialization.DataFormat.XML:
				{
					XmlWriterSettings xmlWriterSetting = new XmlWriterSettings();
					xmlWriterSetting.CheckCharacters = false;
					xmlWriterSetting.OmitXmlDeclaration = true;
					this.xmlWriter = XmlWriter.Create(this.textWriter, xmlWriterSetting);
					this.xmlSerializer = new Serializer(this.xmlWriter);
					return;
				}
				default:
				{
					return;
				}
			}
		}
예제 #17
1
        protected virtual void WriteItem(XmlWriter writer, string baseUrl, SiteMapEntry item)
        {
            // <url>
            if (item.Url.StartsWith("http")) return;
            
            writer.WriteStartElement("url");
#if DEBUG2           
            if (!string.IsNullOrEmpty(item.ID))
                writer.WriteElementString("id", item.ID);

            if (!string.IsNullOrEmpty(item.Title))
                writer.WriteElementString("title", item.Title);

            if (!string.IsNullOrEmpty(item.Class))
                writer.WriteElementString("class", item.Class);
#endif   
            writer.WriteElementString("loc", baseUrl + item.Url);
            
            if (item.LastModified.HasValue)
                 writer.WriteElementString("lastmod", item.LastModified.Value.ToString("yyyy-MM-dd")); // Google doesn't like IS0 8601/W3C 
            
            if (item.ChangeFrequency != ChangeFrequencyEnum.Undefined)
                writer.WriteElementString("changefreq", item.ChangeFrequency.ToString().ToLowerInvariant());
            
            writer.WriteElementString("priority", item.Priority.ToString(CultureInfo.InvariantCulture)); 

            // </url>
            writer.WriteEndElement();
        }
 public override void WritePaymentSpecificXml(XmlWriter xmlw)
 {
     if (_paymentMethod != null)
     {
         WriteSimpleElement(xmlw, "paymentmethod", _paymentMethod.Value);
     }
 }
 internal override void WriteTo(XmlWriter xml)
 {
     TraceHelper.WriteTraceSource(xml, this.traceSource);
     TraceHelper.WriteEnId(xml, this.enTraceId);
     xml.WriteElementString("EnlistmentType", this.enType.ToString());
     xml.WriteElementString("EnlistmentOptions", this.enOptions.ToString());
 }
 public override void WriteTo(XmlWriter w)
 {
     if (this.fSpecified)
     {
         base.WriteTo(w);
     }
 }
 public override void Write(XmlWriter writer)
 {
     writer.WriteStartElement("sequence", NAMESPACE);
     foreach (var particles in Particles)
         particles.Write(writer);
     writer.WriteEndElement();
 }
예제 #22
0
        public void Serialize(DbDatabaseMapping databaseMapping, DbProviderInfo providerInfo, XmlWriter xmlWriter)
        {
            //Contract.Requires(xmlWriter != null);
            //Contract.Requires(databaseMapping != null);
            //Contract.Requires(providerInfo != null);
            Contract.Assert(databaseMapping.Model != null);
            Contract.Assert(databaseMapping.Database != null);

            _xmlWriter = xmlWriter;
            _databaseMapping = databaseMapping;
            _version = databaseMapping.Model.Version;
            _providerInfo = providerInfo;
            _namespace = _version == DataModelVersions.Version3 ? EdmXmlNamespaceV3 : EdmXmlNamespaceV2;

            _xmlWriter.WriteStartDocument();

            using (Element("Edmx", "Version", string.Format(CultureInfo.InvariantCulture, "{0:F1}", _version)))
            {
                WriteEdmxRuntime();
                WriteEdmxDesigner();
            }

            _xmlWriter.WriteEndDocument();
            _xmlWriter.Flush();
        }
        private static void WriteReportFieldsXml(XmlWriter writer, Report report)
        {
            writer.WriteStartElement("Fields");

            foreach (var field in report.Fields.Where(field => field.FieldType != FieldType.SectionRepeater))
            {
                writer.WriteStartElement("Field-" + field.FieldType);
                writer.WriteAttributeString("Label", field.Label);

                if (field.FieldType != FieldType.CheckList && field.FieldType != FieldType.Location)
                {
                    writer.WriteString(field.Value);
                }
                else
                {
                    foreach (var item in field.ChildItems)
                    {
                        writer.WriteElementString(item.Item, item.Value);
                    }
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
예제 #24
0
 public override void WriteXml(XmlWriter writer)
 {
     writer.WriteElementString("Format", Format);
     writer.WriteStartElement("OnlineResource", Namespace);
     OnlineResource.WriteXml(writer);
     writer.WriteEndElement();
 }
예제 #25
0
파일: Iir.cs 프로젝트: ufcpp/UfcppSample
		public override void ToXml(XmlWriter xwriter)
		{
			xwriter.WriteStartElement("IirFilter");
			xwriter.WriteElementString("CoefA", Util.ArrayToString(this.CoefA));
			xwriter.WriteElementString("CoefB", Util.ArrayToString(this.CoefB));
			xwriter.WriteEndElement();
		}
예제 #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlExceptionFormatter"/> class using the specified <see cref="XmlWriter"/> and <see cref="Exception"/> objects.
        /// </summary>
        /// <param name="xmlWriter">The <see cref="XmlWriter"/> in which to write the XML.</param>
        /// <param name="exception">The <see cref="Exception"/> to format.</param>
        public XmlExceptionFormatter(XmlWriter xmlWriter, Exception exception)
            : base(exception)
        {
            if (xmlWriter == null) throw new ArgumentNullException("xmlWriter");

            this.xmlWriter = xmlWriter;
        }
        public static void WriteXml(XmlWriter writer, string key, Property value)
        {
            writer.WriteStartElement("PropertyEntry");

            writer.WriteAttributeString("Key", key);

            var type = value.GetType();
            try
            {
                var ser = GetSerializer(type);
                writer.WriteAttributeString("Type", type.AssemblyQualifiedName);
                ser.Serialize(writer, value);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Serialization failed: " + ex.Message);
                Console.WriteLine("Property Key: " + key);
                Console.WriteLine("Property Value: " + value);
                Console.WriteLine("Property Type Name: " + type.Name);
                Console.WriteLine("Property Type Qualified Name: " + type.AssemblyQualifiedName);
                Console.WriteLine("Stacktrace: " + ex.StackTrace);
            }

            writer.WriteEndElement();
        }
예제 #28
0
        protected override void WriteTokenCore( XmlWriter writer, System.IdentityModel.Tokens.SecurityToken token )
        {
            if ( writer == null )
                throw new ArgumentNullException( "writer" );

            if ( token == null )
                throw new ArgumentNullException( "token" );

            var c = token as SecurityToken;
            if ( c != null )
            {
                writer.WriteStartElement( Constants.UsernameTokenPrefix, Constants.UsernameTokenName, Constants.UsernameTokenNamespace );
                writer.WriteAttributeString( Constants.WsUtilityPrefix, Constants.IdAttributeName, Constants.WsUtilityNamespace, token.Id );
                writer.WriteElementString( Constants.UsernameElementName, Constants.UsernameTokenNamespace, c.Info.Username );
                writer.WriteStartElement( Constants.UsernameTokenPrefix, Constants.PasswordElementName, Constants.UsernameTokenNamespace );
                writer.WriteAttributeString( Constants.TypeAttributeName, Constants.PasswordDigestType );
                writer.WriteValue( c.GetPasswordDigestAsBase64() );
                writer.WriteEndElement();
                writer.WriteElementString( Constants.NonceElementName, Constants.UsernameTokenNamespace, c.GetNonceAsBase64() );
                writer.WriteElementString( Constants.CreatedElementName, Constants.WsUtilityNamespace, c.GetCreatedAsString() );
                writer.WriteEndElement();
                writer.Flush();
            }
            else
                base.WriteTokenCore( writer, token );
        }
        /// <summary>
        /// Generates  output data in html form
        /// </summary>
        /// <param name="writer">output stream</param>
        /// <param name="indent">number of indentations</param>
        internal override void DrawHtml(XmlWriter writer, int indent)
        {
            if (Operation == XmlDiffViewOperation.Change)
            {
                Debug.Assert(this.declarationValue != ChangeInformation.Subset);

                XmlDiffView.HtmlStartRow(writer);
                this.DrawLinkNode(writer);
                XmlDiffView.HtmlStartCell(writer, indent);
                XmlDiffView.HtmlWriteString(writer, Tags.XmlDeclarationBegin);
                XmlDiffView.HtmlWriteString(writer, XmlDiffViewOperation.Change, this.declarationValue);
                XmlDiffView.HtmlWriteString(writer, Tags.XmlDeclarationEnd);

                XmlDiffView.HtmlEndCell(writer);
                XmlDiffView.HtmlStartCell(writer, indent);

                XmlDiffView.HtmlWriteString(writer, Tags.XmlDeclarationBegin);
                XmlDiffView.HtmlWriteString(writer, XmlDiffViewOperation.Change, ChangeInformation.Subset);
                XmlDiffView.HtmlWriteString(writer, Tags.XmlDeclarationEnd);

                XmlDiffView.HtmlEndCell(writer);
                XmlDiffView.HtmlEndRow(writer);
            }
            else
            {
                DrawHtmlNoChange(writer, indent);
            }
        }
예제 #30
0
		public void Save(object obj, XmlWriter writer)
		{
			Type t = obj.GetType();
		
//			writer.WriteStartElement(GetTypeName(t));
//			System.Console.WriteLine("\tSave <{0}>",GetTypeName(t));
			                        
			writer.WriteStartElement(obj.GetType().Name);
			
			PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);
			PropertyInfo [] propertyInfos = new PropertyInfo[properties.Count];
			
			for (int i = 0;i < properties.Count ; i ++){
				propertyInfos[i] = t.GetProperty(properties[i].Name);
			}
			
			foreach (PropertyInfo info in propertyInfos) {
				if (info ==  null){
					continue;
				}
				if (!info.CanRead) continue;
				
				if (info.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Length != 0) continue;
				object val = info.GetValue(obj, null);
				if (val == null) continue;
				if (val is ICollection) {
//					PropertyInfo pinfo = t.GetProperty(info.Name);
//					Console.WriteLine("pinfo {0}",pinfo.Name);
					if (info.Name.StartsWith("Contr")) {
						writer.WriteStartElement("Items");
					} else {
					writer.WriteStartElement(info.Name);
					}
					foreach (object element in (ICollection)val) {
						Save(element, writer);
					}
					
					writer.WriteEndElement();
				} else {
					if (!info.CanWrite) continue;
				
					TypeConverter c = TypeDescriptor.GetConverter(info.PropertyType);
					if (c.CanConvertFrom(typeof(string)) && c.CanConvertTo(typeof(string))) {
						try {
							writer.WriteElementString(info.Name, c.ConvertToInvariantString(val));
						} catch (Exception ex) {
							writer.WriteComment(ex.ToString());
						}
					} else if (info.PropertyType == typeof(Type)) {
						writer.WriteElementString(info.Name, ((Type)val).AssemblyQualifiedName);
					} else {
//						System.Diagnostics.Trace.WriteLine("Serialize Pagelayout");
//						writer.WriteStartElement(info.Name);
//						Save(val, writer);
//						writer.WriteEndElement();
					}
				}
			}
			writer.WriteEndElement();
		}
예제 #31
0
 void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
 {
     this.WriteXml(writer);
 }
예제 #32
0
        protected override void WriteElements(Microsoft.VisualStudio.Modeling.SerializationContext serializationContext, Microsoft.VisualStudio.Modeling.ModelElement element, System.Xml.XmlWriter writer)
        {
            base.WriteElements(serializationContext, element, writer);

            //  writer.WriteStartElement("custom");
            //  writer.WriteCData("my custom stuff here!");
            //  writer.WriteEndElement();
        }
 public override void buildXml(System.Xml.XmlWriter xmlWriter)
 {
     throw new NotImplementedException();
 }
예제 #34
0
 public void Save(System.Xml.XmlWriter xmlWriter)
 {
     XTypedServices.Save(xmlWriter, Untyped);
 }
 public abstract void buildXml(System.Xml.XmlWriter xmlWriter);
예제 #36
0
            /// <summary>
            /// Formats the token sequence to the writer
            /// </summary>
            /// <param name="writer"></param>
            /// <param name="tokens"></param>
            public void Format(System.Xml.XmlWriter writer, IEnumerable <Token <MarkupTokenType> > tokens)
            {
                if (writer == null)
                {
                    throw new ArgumentNullException("writer");
                }
                if (tokens == null)
                {
                    throw new ArgumentNullException("tokens");
                }

                int depth = 0;

                IStream <Token <MarkupTokenType> > stream = Stream <Token <MarkupTokenType> > .Create(tokens);

                Token <MarkupTokenType> token = stream.Peek();

                try
                {
                    while (!stream.IsCompleted)
                    {
                        switch (token.TokenType)
                        {
                        case MarkupTokenType.ElementBegin:
                        {
                            depth++;
                            writer.WriteStartElement(token.Name.Prefix, token.Name.LocalName, token.Name.NamespaceUri);

                            stream.Pop();
                            token = stream.Peek();
                            break;
                        }

                        case MarkupTokenType.ElementVoid:
                        {
                            writer.WriteStartElement(token.Name.Prefix, token.Name.LocalName, token.Name.NamespaceUri);

                            stream.Pop();
                            token = stream.Peek();

                            while (!stream.IsCompleted && token.TokenType == MarkupTokenType.Attribute)
                            {
                                this.FormatAttribute(writer, stream);
                                token = stream.Peek();
                            }

                            writer.WriteEndElement();
                            break;
                        }

                        case MarkupTokenType.ElementEnd:
                        {
                            depth--;
                            writer.WriteEndElement();

                            stream.Pop();
                            token = stream.Peek();
                            break;
                        }

                        case MarkupTokenType.Attribute:
                        {
                            this.FormatAttribute(writer, stream);
                            token = stream.Peek();
                            break;
                        }

                        case MarkupTokenType.Primitive:
                        {
                            ITextFormattable <MarkupTokenType> formattable = token.Value as ITextFormattable <MarkupTokenType>;
                            if (formattable != null)
                            {
                                formattable.Format(this, new XmlWriterAdapter(writer));
                            }
                            else
                            {
                                writer.WriteString(token.ValueAsString());
                            }

                            stream.Pop();
                            token = stream.Peek();
                            break;
                        }

                        default:
                        {
                            throw new TokenException <MarkupTokenType>(
                                      token,
                                      String.Format(ErrorUnexpectedToken, token.TokenType));
                        }
                        }
                    }

                    while (depth-- > 0)
                    {
                        // auto close otherwise XmlWriter will choke
                        writer.WriteEndElement();
                    }
                }
                catch (Exception ex)
                {
                    throw new TokenException <MarkupTokenType>(token, ex.Message, ex);
                }
            }
예제 #37
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="writer"></param>
 public XmlWriterAdapter(System.Xml.XmlWriter writer)
 {
     this.Writer = writer;
 }
예제 #38
0
 /// <summary>
 /// Serializes the DiceHandler object.
 /// </summary>
 /// <param name="writer">The xml writer to use when writing.</param>
 public void WriteXml(System.Xml.XmlWriter writer)
 {
     DiceState.WriteXml(writer);
 }
예제 #39
0
 void System.Xml.Serialization.IXmlSerializable.WriteXml(Xml.XmlWriter writer)
 {
     writer.WriteValue(this.ToString());
 }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

                if (TrackCancel == null)
                {
                    TrackCancel = new CancelTrackerClass();
                }

                IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter;
                IGPValue     inputFeatureDatasetGPValue   = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter);
                IGPValue     outputOSMFileGPValue         = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber));

                // get the name of the feature dataset
                int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");

                string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1);


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

                System.Xml.XmlWriter xmlWriter = null;

                try
                {
                    xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings);
                }
                catch (Exception ex)
                {
                    message.AddError(120021, ex.Message);
                    return;
                }

                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("osm");                                             // start the osm root node
                xmlWriter.WriteAttributeString("version", "0.6");                               // add the version attribute
                xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute

                // write all the nodes
                // use a feature search cursor to loop through all the known points and write them out as osm node

                IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer;

                if (osmFeatureClasses == null)
                {
                    message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name));
                    return;
                }

                IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt");

                if (osmPointFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt"));
                    return;
                }

                // check the extension of the point feature class to determine its version
                int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion();

                IFeatureCursor searchCursor = null;

                System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces();
                xmlnsEmpty.Add("", "");

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg"));
                int pointCounter = 0;

                string nodesExportedMessage = String.Empty;

                // collect the indices for the point feature class once
                int pointOSMIDFieldIndex     = osmPointFeatureClass.Fields.FindField("OSMID");
                int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset");
                int pointVersionFieldIndex   = osmPointFeatureClass.Fields.FindField("osmversion");
                int pointUIDFieldIndex       = osmPointFeatureClass.Fields.FindField("osmuid");
                int pointUserFieldIndex      = osmPointFeatureClass.Fields.FindField("osmuser");
                int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp");
                int pointVisibleFieldIndex   = osmPointFeatureClass.Fields.FindField("osmvisible");
                int pointTagsFieldIndex      = osmPointFeatureClass.Fields.FindField("osmTags");

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPointFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node));

                    IFeature currentFeature = searchCursor.NextFeature();

                    IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == true)
                        {
                            // convert the found point feature into a osm node representation to store into the OSM XML file
                            node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion);

                            pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);

                            // increase the point counter to later status report
                            pointCounter++;

                            currentFeature = searchCursor.NextFeature();
                        }
                        else
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loader so far
                            nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                            message.AddMessage(nodesExportedMessage);

                            return;
                        }
                    }
                }

                nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                message.AddMessage(nodesExportedMessage);

                // next loop through the line and polygon feature classes to export those features as ways
                // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table
                IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln");

                if (osmLineFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln"));
                    return;
                }

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg"));

                // as we are looping through the line and polygon feature classes let's collect the multi-part features separately
                // as they are considered relations in the OSM world
                List <relation> multiPartElements = new List <relation>();

                System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way));
                int    lineCounter         = 0;
                int    relationCounter     = 0;
                string waysExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmLineFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int lineOSMIDFieldIndex     = osmLineFeatureClass.Fields.FindField("OSMID");
                    int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset");
                    int lineVersionFieldIndex   = osmLineFeatureClass.Fields.FindField("osmversion");
                    int lineUIDFieldIndex       = osmLineFeatureClass.Fields.FindField("osmuid");
                    int lineUserFieldIndex      = osmLineFeatureClass.Fields.FindField("osmuser");
                    int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp");
                    int lineVisibleFieldIndex   = osmLineFeatureClass.Fields.FindField("osmvisible");
                    int lineTagsFieldIndex      = osmLineFeatureClass.Fields.FindField("osmTags");
                    int lineMembersFieldIndex   = osmLineFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }


                IFeatureClass     osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply");
                IFeatureWorkspace commonWorkspace        = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace;

                if (osmPolygonFeatureClass == null)
                {
                    message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply"));
                    return;
                }

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPolygonFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int polygonOSMIDFieldIndex     = osmPolygonFeatureClass.Fields.FindField("OSMID");
                    int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset");
                    int polygonVersionFieldIndex   = osmPolygonFeatureClass.Fields.FindField("osmversion");
                    int polygonUIDFieldIndex       = osmPolygonFeatureClass.Fields.FindField("osmuid");
                    int polygonUserFieldIndex      = osmPolygonFeatureClass.Fields.FindField("osmuser");
                    int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp");
                    int polygonVisibleFieldIndex   = osmPolygonFeatureClass.Fields.FindField("osmvisible");
                    int polygonTagsFieldIndex      = osmPolygonFeatureClass.Fields.FindField("osmTags");
                    int polygonMembersFieldIndex   = osmPolygonFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }

                waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                message.AddMessage(waysExportedMessage);


                // now let's go through the relation table
                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg"));
                ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation");

                if (relationTable == null)
                {
                    message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation"));
                    return;
                }


                System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation));
                string relationsExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    ICursor rowCursor = relationTable.Search(null, false);
                    comReleaser.ManageLifetime(rowCursor);

                    IRow currentRow = rowCursor.NextRow();

                    // collect the indices for the relation table once
                    int relationOSMIDFieldIndex     = relationTable.Fields.FindField("OSMID");
                    int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset");
                    int relationVersionFieldIndex   = relationTable.Fields.FindField("osmversion");
                    int relationUIDFieldIndex       = relationTable.Fields.FindField("osmuid");
                    int relationUserFieldIndex      = relationTable.Fields.FindField("osmuser");
                    int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp");
                    int relationVisibleFieldIndex   = relationTable.Fields.FindField("osmvisible");
                    int relationTagsFieldIndex      = relationTable.Fields.FindField("osmTags");
                    int relationMembersFieldIndex   = relationTable.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;


                    while (currentRow != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loaded so far
                            relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                            message.AddMessage(relationsExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion);
                        relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty);

                        // increase the line counter for later status report
                        relationCounter++;

                        currentRow = rowCursor.NextRow();
                    }
                }

                // lastly let's serialize the collected multipart-geometries back into relation elements
                foreach (relation currentRelation in multiPartElements)
                {
                    if (TrackCancel.Continue() == false)
                    {
                        // properly close the document
                        xmlWriter.WriteEndElement();  // closing the osm root element
                        xmlWriter.WriteEndDocument(); // finishing the document

                        xmlWriter.Close();            // closing the document

                        // report the number of elements loaded so far
                        relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                        message.AddMessage(relationsExportedMessage);

                        return;
                    }

                    relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty);
                    relationCounter++;
                }

                relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                message.AddMessage(relationsExportedMessage);


                xmlWriter.WriteEndElement();  // closing the osm root element
                xmlWriter.WriteEndDocument(); // finishing the document

                xmlWriter.Close();            // closing the document
            }
            catch (Exception ex)
            {
                message.AddError(120026, ex.Message);
            }
        }