System.Xml.XmlWriter.WriteStartElement(string)

Here are the examples of the csharp api System.Xml.XmlWriter.WriteStartElement(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1103 Examples 7

19 Source : ReferenceLinks.cs
with MIT License
from actions

void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(List<ReferenceLink>));

            foreach (var item in this.referenceLinks)
            {
                writer.WriteStartElement("item");

                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, item.Key);
                writer.WriteEndElement();

                writer.WriteStartElement("value");
                var links = item.Value as List<ReferenceLink>;
                if (links == null)
                {
                    links = new List<ReferenceLink>()
                    {
                        (ReferenceLink)item.Value
                    };
                }

                valueSerializer.Serialize(writer, links);
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
        }

19 Source : SiteMapHandler.cs
with MIT License
from Adoxio

public void ProcessRequest(HttpContext context)
		{
			context.Response.ContentEncoding = Encoding.UTF8;
			context.Response.ContentType = "text/xml";

			using (var xml = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
			{
				xml.WriteStartDoreplacedent();

				xml.WriteStartElement("urlset");
				xml.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

				ProcessNode(xml, "http://" + context.Request.ServerVariables["HTTP_HOST"], SiteMap.Provider.RootNode);

				xml.WriteEndDoreplacedent();
			}
		}

19 Source : ForumSiteMapHandler.cs
with MIT License
from Adoxio

public void ProcessRequest(HttpContext context)
		{
			context.Response.ContentEncoding = Encoding.UTF8;
			context.Response.ContentType = "text/xml";

			using (var xml = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
			{
				xml.WriteStartDoreplacedent();

				xml.WriteStartElement("urlset");
				xml.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

				foreach (var forum in PortalContext.Current.ServiceContext.GetForums())
				{
					ProcessNode(xml, "http://" + context.Request.ServerVariables["HTTP_HOST"], forum);
				}

				xml.WriteEndDoreplacedent();
			}
		}

19 Source : ForumSiteMapHandler.cs
with MIT License
from Adoxio

public void ProcessNode(XmlTextWriter xml, string urlPrefix, Enreplacedy forum)
		{
			forum.replacedertEnreplacedyName("adx_communityforum");

			var context = PortalContext.Current.ServiceContext;

			var threads = forum.GetRelatedEnreplacedies(context, "adx_communityforum_communityforumthread");

			foreach (var thread in threads)
			{
				xml.WriteStartElement("url");
				xml.WriteElementString("loc", urlPrefix + context.GetUrl(thread));
				xml.WriteElementString("lastmod", thread.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow).ToString("yyyy-MM-dd"));
				xml.WriteEndElement();
			}
		}

19 Source : SiteMapHandler.cs
with MIT License
from Adoxio

public void ProcessNode(XmlTextWriter xml, string urlPrefix, SiteMapNode node)
		{
			xml.WriteStartElement("url");
			xml.WriteElementString("loc", urlPrefix + node.Url);

			if (node is CrmSiteMapNode)
			{
				xml.WriteElementString("lastmod", ((CrmSiteMapNode)node).LastModified.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
			}

			xml.WriteEndElement();

			foreach (SiteMapNode child in node.ChildNodes)
			{
				ProcessNode(xml, urlPrefix, child);
			}
		}

19 Source : HtmlFromXamlConverter.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
        {
            Debug.replacedert(xamlReader.NodeType == XmlNodeType.Element);

            if (htmlWriter == null)
            {
                // Skipping mode; recurse into the xaml element without any output
                WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
            }
            else
            {
                string htmlElementName = null;

                switch (xamlReader.Name)
                {
                    case "Run" :
                    case "Span":
                        htmlElementName = "SPAN";
                        break;
                    case "InlineUIContainer":
                        htmlElementName = "SPAN";
                        break;
                    case "Bold":
                        htmlElementName = "B";
                        break;
                    case "Italic" :
                        htmlElementName = "I";
                        break;
                    case "Paragraph" :
                        htmlElementName = "P";
                        break;
                    case "BlockUIContainer":
                        htmlElementName = "DIV";
                        break;
                    case "Section":
                        htmlElementName = "DIV";
                        break;
                    case "Table":
                        htmlElementName = "TABLE";
                        break;
                    case "TableColumn":
                        htmlElementName = "COL";
                        break;
                    case "TableRowGroup" :
                        htmlElementName = "TBODY";
                        break;
                    case "TableRow" :
                        htmlElementName = "TR";
                        break;
                    case "TableCell" :
                        htmlElementName = "TD";						
                        break;
                    case "List" :
                        string marker = xamlReader.GetAttribute("MarkerStyle");
                        if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box")
							htmlElementName = "UL";
						else
                            htmlElementName = "OL";
                        break;
                    case "Lisreplacedem" :
                        htmlElementName = "LI";
                        break;
					case "Hyperlink" :
						htmlElementName = "A";
						break;
					case "LineBreak" :
						htmlWriter.WriteRaw("<BR />");
						break;
                    default :
                        htmlElementName = null; // Ignore the element
                        break;
                }

                if (htmlWriter != null && !String.IsNullOrEmpty(htmlElementName))
                {
                    htmlWriter.WriteStartElement(htmlElementName);

                    WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);

                    WriteElementContent(xamlReader, htmlWriter, inlineStyle);

                    htmlWriter.WriteEndElement();
                }
                else
                {
                    // Skip this unrecognized xaml element
                    WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
                }
            }
        }

19 Source : HtmlFromXamlConverter.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private static bool WriteFlowDoreplacedent(XmlTextReader xamlReader, XmlTextWriter htmlWriter)
        {
            if (!ReadNextToken(xamlReader))
            {
                // Xaml content is empty - nothing to convert
                return false;
            }

            if (xamlReader.NodeType != XmlNodeType.Element || xamlReader.Name != "FlowDoreplacedent")
            {
                // Root FlowDoreplacedent elemet is missing
                return false;
            }

            // Create a buffer StringBuilder for collecting css properties for inline STYLE attributes
            // on every element level (it will be re-initialized on every level).
            StringBuilder inlineStyle = new StringBuilder();

            htmlWriter.WriteStartElement("HTML");
            htmlWriter.WriteStartElement("BODY");

            WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);

            WriteElementContent(xamlReader, htmlWriter, inlineStyle);

            htmlWriter.WriteEndElement();
            htmlWriter.WriteEndElement();

            return true;
        }

19 Source : DHLProvider.cs
with MIT License
from alexeybusygin

private string BuildRatesRequestMessage(
            DateTime requestDateTime,
            DateTime pickupDateTime,
            string messageReference)
        {
            var requestCulture = CultureInfo.CreateSpecificCulture("en-US");
            var xmlSettings = new XmlWriterSettings()
            {
                Indent = true,
                Encoding = Encoding.UTF8
            };

            var isDomestic = Shipment.OriginAddress.CountryCode == Shipment.DestinationAddress.CountryCode;
            var isDutiable = !Shipment.HasDoreplacedentsOnly && !isDomestic;

            using (var memoryStream = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(memoryStream, xmlSettings))
                {
                    writer.WriteStartDoreplacedent();
                    writer.WriteStartElement("p", "DCTRequest", "http://www.dhl.com");
                    writer.WriteStartElement("GetQuote");

                    writer.WriteStartElement("Request");
                    writer.WriteStartElement("ServiceHeader");
                    writer.WriteElementString("MessageTime", requestDateTime.ToString("O", requestCulture));
                    writer.WriteElementString("MessageReference", messageReference);
                    writer.WriteElementString("SiteID", _configuration.SiteId);
                    writer.WriteElementString("Preplacedword", _configuration.Preplacedword);
                    writer.WriteEndElement(); // </ServiceHeader>
                    writer.WriteEndElement(); // </Request>

                    WriteAddress(writer, "From", Shipment.OriginAddress);

                    writer.WriteStartElement("BkgDetails");
                    writer.WriteElementString("PaymentCountryCode", Shipment.OriginAddress.CountryCode);
                    writer.WriteElementString("Date", pickupDateTime.ToString("yyyy-MM-dd", requestCulture));
                    writer.WriteElementString("ReadyTime", $"PT{pickupDateTime:HH}H{pickupDateTime:mm}M");
                    writer.WriteElementString("ReadyTimeGMTOffset", pickupDateTime.ToString("zzz", requestCulture));
                    writer.WriteElementString("DimensionUnit", "IN");
                    writer.WriteElementString("WeightUnit", "LB");

                    writer.WriteStartElement("Pieces");
                    for (var i = 0; i < Shipment.Packages.Count; i++)
                    {
                        writer.WriteStartElement("Piece");
                        writer.WriteElementString("PieceID", $"{i + 1}");
                        writer.WriteElementString("Height", Shipment.Packages[i].RoundedHeight.ToString(requestCulture));
                        writer.WriteElementString("Depth", Shipment.Packages[i].RoundedLength.ToString(requestCulture));
                        writer.WriteElementString("Width", Shipment.Packages[i].RoundedWidth.ToString(requestCulture));
                        writer.WriteElementString("Weight", Shipment.Packages[i].RoundedWeight.ToString(requestCulture));
                        writer.WriteEndElement(); // </Piece>
                    }
                    writer.WriteEndElement(); // </Pieces>

                    if (!string.IsNullOrEmpty(_configuration.PaymentAccountNumber))
                    {
                        writer.WriteElementString("PaymentAccountNumber", _configuration.PaymentAccountNumber);
                    }
                    writer.WriteElementString("IsDutiable", isDutiable ? "Y" : "N");
                    writer.WriteElementString("NetworkTypeCode", "AL");

                    writer.WriteStartElement("QtdShp");
                    if (_configuration.ServicesIncluded.Any())
                    {
                        foreach (var serviceCode in _configuration.ServicesIncluded)
                        {
                            writer.WriteElementString("GlobalProductCode", serviceCode.ToString());
                        }
                    }
                    if (Shipment.Options.SaturdayDelivery)
                    {
                        writer.WriteStartElement("QtdShpExChrg");
                        writer.WriteElementString("SpecialServiceType", isDomestic ? "AG" : "AA");
                        writer.WriteEndElement(); // </QtdShpExChrg>
                    }
                    writer.WriteEndElement(); // </QtdShp>

                    var totalInsurance = Shipment.Packages.Sum(p => p.InsuredValue);
                    if (totalInsurance > 0)
                    {
                        writer.WriteElementString("InsuredValue", $"{totalInsurance:N}");
                        writer.WriteElementString("InsuredCurrency", "USD");
                    }

                    writer.WriteEndElement(); // </BkgDetails>

                    WriteAddress(writer, "To", Shipment.DestinationAddress);

                    if (isDutiable)
                    {
                        writer.WriteStartElement("Dutiable");
                        writer.WriteElementString("DeclaredCurrency", "USD");
                        writer.WriteElementString("DeclaredValue", $"{totalInsurance:N}");
                        writer.WriteEndElement(); // </Dutiable>
                    }

                    writer.WriteEndElement(); // </GetQuote>
                    writer.WriteEndElement(); // </p:DCTRequest>
                    writer.WriteEndDoreplacedent();
                    writer.Flush();
                    writer.Close();
                }
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }

19 Source : UPSProvider.cs
with MIT License
from alexeybusygin

private string BuildRatesRequestMessage()
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var writer = new XmlTextWriter(memoryStream, Encoding.UTF8))
                {
                    writer.WriteStartDoreplacedent();
                    writer.WriteStartElement("AccessRequest");
                    writer.WriteAttributeString("lang", "en-US");
                    writer.WriteElementString("AccessLicenseNumber", _licenseNumber);
                    writer.WriteElementString("UserId", _userId);
                    writer.WriteElementString("Preplacedword", _preplacedword);
                    writer.WriteEndDoreplacedent();

                    writer.WriteStartDoreplacedent();
                    writer.WriteStartElement("RatingServiceSelectionRequest");
                    writer.WriteAttributeString("lang", "en-US");

                    writer.WriteStartElement("Request");
                    writer.WriteElementString("RequestAction", "Rate");
                    writer.WriteElementString("RequestOption", string.IsNullOrWhiteSpace(_serviceDescription) ? "Shop" : _serviceDescription);
                    writer.WriteElementString("SubVersion", "1801");
                    writer.WriteEndElement(); // </Request>

                    writer.WriteStartElement("PickupType");
                    writer.WriteElementString("Code", "03");
                    writer.WriteEndElement(); // </PickupType>

                    writer.WriteStartElement("CustomerClreplacedification");
                    if (UseRetailRates)
                    {
                        writer.WriteElementString("Code", "04"); //04 gets retail rates
                    }
                    else
                    {
                        writer.WriteElementString("Code", string.IsNullOrWhiteSpace(_shipperNumber) ? "01" : "00"); // 00 gets shipper number rates, 01 for daily rates
                    }
                    writer.WriteEndElement(); // </CustomerClreplacedification

                    writer.WriteStartElement("Shipment");

                    writer.WriteStartElement("Shipper");
                    if (!string.IsNullOrWhiteSpace(_shipperNumber))
                    {
                        writer.WriteElementString("ShipperNumber", _shipperNumber);
                    }
                    writer.WriteStartElement("Address");
                    writer.WriteElementString("PostalCode", Shipment.OriginAddress.PostalCode);
                    writer.WriteElementString("CountryCode", Shipment.OriginAddress.CountryCode);
                    writer.WriteEndElement(); // </Address>
                    writer.WriteEndElement(); // </Shipper>

                    writer.WriteStartElement("ShipTo");
                    writer.WriteStartElement("Address");
                    if (!string.IsNullOrWhiteSpace(Shipment.DestinationAddress.State))
                    {
                        writer.WriteElementString("StateProvinceCode", Shipment.DestinationAddress.State);
                    }
                    if (!string.IsNullOrWhiteSpace(Shipment.DestinationAddress.PostalCode))
                    {
                        writer.WriteElementString("PostalCode", Shipment.DestinationAddress.PostalCode);
                    }
                    writer.WriteElementString("CountryCode", Shipment.DestinationAddress.CountryCode);
                    if (Shipment.DestinationAddress.IsResidential)
                    {
                        writer.WriteElementString("ResidentialAddressIndicator", "true");
                    }
                    writer.WriteEndElement(); // </Address>
                    writer.WriteEndElement(); // </ShipTo>

                    if (!string.IsNullOrWhiteSpace(_serviceDescription))
                    {
                        writer.WriteStartElement("Service");
                        writer.WriteElementString("Code", _serviceDescription.ToUpsShipCode());
                        writer.WriteEndElement(); //</Service>
                    }
                    if (UseNegotiatedRates)
                    {
                        writer.WriteStartElement("RateInformation");
                        writer.WriteElementString("NegotiatedRatesIndicator", "");
                        writer.WriteEndElement();// </RateInformation>
                    }
                    if (Shipment.Options.ShippingDate != null)
                    {
                        writer.WriteStartElement("DeliveryTimeInformation");
                        writer.WriteElementString("PackageBillType", "03");
                        writer.WriteStartElement("Pickup");
                        writer.WriteElementString("Date", Shipment.Options.ShippingDate.Value.ToString("yyyyMMdd"));
                        writer.WriteElementString("Time", "1000");
                        writer.WriteEndElement();// </Pickup>
                        writer.WriteEndElement();// </DeliveryTimeInformation>
                    }
                    if (Shipment.Options.SaturdayDelivery)
                    {
                        writer.WriteStartElement("ShipmentServiceOptions");
                        writer.WriteElementString("SaturdayDelivery", "");
                        writer.WriteEndElement();// </ShipmentServiceOptions>
                    }
                    if (Shipment.HasDoreplacedentsOnly)
                    {
                        writer.WriteElementString("DoreplacedentsOnly", "true");
                    }

                    for (var i = 0; i < Shipment.Packages.Count; i++)
                    {
                        writer.WriteStartElement("Package");
                        writer.WriteStartElement("PackagingType");
                        writer.WriteElementString("Code", "02");
                        writer.WriteEndElement(); //</PackagingType>
                        writer.WriteStartElement("PackageWeight");
                        writer.WriteElementString("Weight", Shipment.Packages[i].RoundedWeight.ToString());
                        writer.WriteEndElement(); // </PackageWeight>
                        writer.WriteStartElement("Dimensions");
                        writer.WriteElementString("Length", Shipment.Packages[i].RoundedLength.ToString());
                        writer.WriteElementString("Width", Shipment.Packages[i].RoundedWidth.ToString());
                        writer.WriteElementString("Height", Shipment.Packages[i].RoundedHeight.ToString());
                        writer.WriteEndElement(); // </Dimensions>
                        writer.WriteStartElement("PackageServiceOptions");
                        writer.WriteStartElement("InsuredValue");
                        writer.WriteElementString("CurrencyCode", "USD");
                        writer.WriteElementString("MonetaryValue", Shipment.Packages[i].InsuredValue.ToString());
                        writer.WriteEndElement(); // </InsuredValue>

                        if (Shipment.Packages[i].SignatureRequiredOnDelivery)
                        {
                            writer.WriteStartElement("DeliveryConfirmation");
                            writer.WriteElementString("DCISType", "2");         // 2 represents Delivery Confirmation Signature Required
                            writer.WriteEndElement(); // </DeliveryConfirmation>
                        }

                        writer.WriteEndElement(); // </PackageServiceOptions>
                        writer.WriteEndElement(); // </Package>
                    }
                    writer.WriteEndElement();   // </Shipment>
                    writer.WriteEndElement();   // </RatingServiceSelectionRequest>

                    writer.WriteEndDoreplacedent();
                    writer.Flush();
                    writer.Close();
                }
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }

19 Source : USPSInternationalProvider.cs
with MIT License
from alexeybusygin

public override async Task GetRates()
        {
            var sb = new StringBuilder();

            var settings = new XmlWriterSettings
            {
                Indent = false,
                OmitXmlDeclaration = true,
                NewLineHandling = NewLineHandling.None
            };

            using (var writer = XmlWriter.Create(sb, settings))
            {
                writer.WriteStartElement("IntlRateV2Request");
                writer.WriteAttributeString("USERID", _userId);

                writer.WriteElementString("Revision", "2");
                var i = 0;
                foreach (var package in Shipment.Packages)
                {
                    //<Package ID="2ND">
                    //  <Pounds>0</Pounds>
                    //  <Ounces>3</Ounces>
                    //  <MailType>Envelope</MailType>
                    //  <ValueOfContents>750</ValueOfContents>
                    //  <Country>Algeria</Country>
                    //  <Container></Container>
                    //  <Size>REGULAR</Size>
                    //  <Width></Width>
                    //  <Length></Length>
                    //  <Height></Height>
                    //  <Girth></Girth>
                    //  <CommercialFlag>N</CommercialFlag>
                    //</Package>

                    writer.WriteStartElement("Package");
                    writer.WriteAttributeString("ID", i.ToString());
                    writer.WriteElementString("Pounds", package.PoundsAndOunces.Pounds.ToString());
                    writer.WriteElementString("Ounces", package.PoundsAndOunces.Ounces.ToString());
                    writer.WriteElementString("MailType", "All");
                    writer.WriteElementString("ValueOfContents", package.InsuredValue.ToString());
                    writer.WriteElementString("Country", Shipment.DestinationAddress.GetCountryName());
                    writer.WriteElementString("Container", "RECTANGULAR");
                    writer.WriteElementString("Size", "REGULAR");
                    writer.WriteElementString("Width", package.RoundedWidth.ToString());
                    writer.WriteElementString("Length", package.RoundedLength.ToString());
                    writer.WriteElementString("Height", package.RoundedHeight.ToString());
                    writer.WriteElementString("Girth", package.CalculatedGirth.ToString());
                    writer.WriteElementString("OriginZip", Shipment.OriginAddress.PostalCode);
                    writer.WriteElementString("CommercialFlag", Commercial ? "Y" : "N");

                    // ContentType must be set to Doreplacedents to get First-Clreplaced International Mail rates
                    if (package is DoreplacedentsPackage)
                    {
                        writer.WriteStartElement("Content");
                        writer.WriteElementString("ContentType", "Doreplacedents");
                        writer.WriteEndElement();
                    }

                    //TODO: Figure out DIM Weights
                    //writer.WriteElementString("Size", package.IsOversize ? "LARGE" : "REGULAR");
                    //writer.WriteElementString("Length", package.RoundedLength.ToString());
                    //writer.WriteElementString("Width", package.RoundedWidth.ToString());
                    //writer.WriteElementString("Height", package.RoundedHeight.ToString());
                    //writer.WriteElementString("Girth", package.CalculatedGirth.ToString());
                    i++;
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.Flush();
            }

            try
            {
                using (var httpClient = new HttpClient())
                {
                    var rateUri = new Uri($"{ProductionUrl}?API=IntlRateV2&XML={sb}");
                    var response = await httpClient.GetStringAsync(rateUri).ConfigureAwait(false);

                    ParseResult(response);
                }
            }
            catch (Exception ex)
            {
                AddInternalError($"USPS International provider exception: {ex.Message}");
            }
        }

19 Source : CSharpNHibernateXmlSourceFileGenerator.cs
with GNU General Public License v3.0
from alexgracianoarj

protected override void WriteFileContent()
        {
            useLazyLoading = Settings.Default.DefaultLazyFetching;
            useLowercaseUnderscored = Settings.Default.UseUnderscoreAndLowercaseInDB;

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;
            settings.Encoding = System.Text.Encoding.Unicode;

            ClreplacedType _clreplaced = (ClreplacedType)Type;
            
            if(_clreplaced.IdGenerator == null)
                idGeneratorType = EnumExtensions.GetDescription(Settings.Default.DefaultIdenreplacedyGenerator);
            else
                idGeneratorType = EnumExtensions.GetDescription((IdenreplacedyGeneratorType)Enum.Parse(typeof(IdenreplacedyGeneratorType), _clreplaced.IdGenerator));
            
            using (XmlWriter xml = XmlWriter.Create(CodeBuilder, settings))
            {
                xml.WriteStartDoreplacedent();
                xml.WriteComment(
                    string.Format(
                    " This code was generated by {0} ", 
                    GetVersionString()
                    ));
                xml.WriteStartElement("hibernate-mapping", "urn:nhibernate-mapping-2.2");
                xml.WriteAttributeString("replacedembly", ProjectName);
                xml.WriteAttributeString("namespace", RootNamespace);
                xml.WriteStartElement("clreplaced");
                xml.WriteAttributeString("name", _clreplaced.Name);
                xml.WriteAttributeString("table", 
                    string.Format("`{0}`",
                    PrefixedText(
                        useLowercaseUnderscored 
                        ? LowercaseAndUnderscoredWord(_clreplaced.Name) 
                        : string.IsNullOrEmpty(_clreplaced.NHMTableName)
                        ? _clreplaced.Name
                        : _clreplaced.NHMTableName
                    )));
                xml.WriteAttributeString("lazy", useLazyLoading.ToString().ToLower());

                List<Operation> ids = _clreplaced.Operations.Where(o => o is Property && o.IsIdenreplacedy).ToList<Operation>();

                if(ids.Count > 1)
                {
                    xml.WriteStartElement("composite-id");
                    foreach (var id in ids)
                    {
                        if(!string.IsNullOrEmpty(id.ManyToOne))
                        {
                            xml.WriteStartElement("key-many-to-one");
                            xml.WriteAttributeString("name", id.Name);
                            xml.WriteAttributeString("column",
                                string.Format("`{0}`",
                                    useLowercaseUnderscored
                                    ? LowercaseAndUnderscoredWord(id.Name)
                                    : string.IsNullOrEmpty(id.NHMColumnName)
                                    ? id.Name
                                    : id.NHMColumnName
                                ));
                            xml.WriteAttributeString("clreplaced", id.Type);
                            xml.WriteEndElement();
                        }
                        else
                        {
                            xml.WriteStartElement("key-property");
                            xml.WriteAttributeString("name", id.Name);
                            xml.WriteAttributeString("column",
                                string.Format("`{0}`",
                                    useLowercaseUnderscored
                                    ? LowercaseAndUnderscoredWord(id.Name)
                                    : string.IsNullOrEmpty(id.NHMColumnName)
                                    ? id.Name
                                    : id.NHMColumnName
                                ));
                            xml.WriteAttributeString("type", id.Type);
                            xml.WriteEndElement();
                        }
                    }
                    xml.WriteEndElement();
                }
                else if (ids.Count == 1)
                {
                    xml.WriteStartElement("id");
                    xml.WriteAttributeString("name", ids[0].Name);
                    xml.WriteAttributeString("column",
                        string.Format("`{0}`",
                            useLowercaseUnderscored
                            ? LowercaseAndUnderscoredWord(ids[0].Name)
                            : string.IsNullOrEmpty(ids[0].NHMColumnName)
                            ? ids[0].Name
                            : ids[0].NHMColumnName
                        ));
                    xml.WriteAttributeString("type", ids[0].Type);
                    xml.WriteStartElement("generator");
                    
                    if (_clreplaced.IdGenerator != "Custom")
                        xml.WriteAttributeString("clreplaced", idGeneratorType);

                    if (_clreplaced.IdGenerator == "HiLo")
                    {
                        HiLoIdenreplacedyGeneratorParameters hiLo = GeneratorParametersDeSerializer.Deserialize<HiLoIdenreplacedyGeneratorParameters>(_clreplaced.GeneratorParameters);
                        
                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "table");
                        xml.WriteValue(hiLo.Table);
                        xml.WriteEndElement();

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "column");
                        xml.WriteValue(hiLo.Column);
                        xml.WriteEndElement();

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "max_lo");
                        xml.WriteValue(hiLo.MaxLo);
                        xml.WriteEndElement();

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "where");
                        xml.WriteValue(hiLo.Where);
                        xml.WriteEndElement();
                    }
                    else if (_clreplaced.IdGenerator == "SeqHiLo")
                    {
                        SeqHiLoIdenreplacedyGeneratorParameters seqHiLo = GeneratorParametersDeSerializer.Deserialize<SeqHiLoIdenreplacedyGeneratorParameters>(_clreplaced.GeneratorParameters);

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "sequence");
                        xml.WriteValue(seqHiLo.Sequence);
                        xml.WriteEndElement();

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "max_lo");
                        xml.WriteValue(seqHiLo.MaxLo);
                        xml.WriteEndElement();
                    }
                    else if (_clreplaced.IdGenerator == "Sequence")
                    {
                        SequenceIdenreplacedyGeneratorParameters sequence = GeneratorParametersDeSerializer.Deserialize<SequenceIdenreplacedyGeneratorParameters>(_clreplaced.GeneratorParameters);

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "sequence");
                        xml.WriteValue(sequence.Sequence);
                        xml.WriteEndElement();
                    }
                    else if (_clreplaced.IdGenerator == "UuidHex")
                    {
                        UuidHexIdenreplacedyGeneratorParameters uuidHex = GeneratorParametersDeSerializer.Deserialize<UuidHexIdenreplacedyGeneratorParameters>(_clreplaced.GeneratorParameters);

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "format_value");
                        xml.WriteValue(uuidHex.Format);
                        xml.WriteEndElement();

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "separator_value");
                        xml.WriteValue(uuidHex.Separator);
                        xml.WriteEndElement();
                    }
                    else if (_clreplaced.IdGenerator == "Foreign")
                    {
                        ForeignIdenreplacedyGeneratorParameters foreign = GeneratorParametersDeSerializer.Deserialize<ForeignIdenreplacedyGeneratorParameters>(_clreplaced.GeneratorParameters);

                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", "property");
                        xml.WriteValue(foreign.Property);
                        xml.WriteEndElement();
                    }
                    else if (_clreplaced.IdGenerator == "Custom")
                    {
                        CustomIdenreplacedyGeneratorParameters custom = GeneratorParametersDeSerializer.Deserialize<CustomIdenreplacedyGeneratorParameters>(_clreplaced.GeneratorParameters);

                        xml.WriteAttributeString("clreplaced", custom.Clreplaced);

                        foreach(var param in custom.Parameters)
                        {
                            xml.WriteStartElement("param");
                            xml.WriteAttributeString("name", param.Name);
                            xml.WriteValue(param.Value);
                            xml.WriteEndElement();
                        }
                    }

                    xml.WriteEndElement();
                    xml.WriteEndElement();
                }

                foreach (var property in _clreplaced.Operations.Where(o => o is Property && !o.IsIdenreplacedy).ToList<Operation>())
                {
                    if (!string.IsNullOrEmpty(property.ManyToOne))
                    {
                        xml.WriteStartElement("many-to-one");
                        xml.WriteAttributeString("name", property.Name);
                        xml.WriteAttributeString("clreplaced", property.Type);
                        xml.WriteAttributeString("column",
                            string.Format("`{0}`",
                                useLowercaseUnderscored
                                ? LowercaseAndUnderscoredWord(property.Name)
                                : string.IsNullOrEmpty(property.NHMColumnName)
                                ? property.Name
                                : property.NHMColumnName
                            ));
                        
                        if (property.IsUnique)
                            xml.WriteAttributeString("unique", "true");
                        
                        xml.WriteAttributeString("not-null", property.IsNotNull.ToString().ToLower());
                        xml.WriteEndElement();
                    }
                    else
                    {
                        xml.WriteStartElement("property");
                        xml.WriteAttributeString("name", property.Name);
                        xml.WriteAttributeString("column",
                            string.Format("`{0}`",
                                useLowercaseUnderscored
                                ? LowercaseAndUnderscoredWord(property.Name)
                                : string.IsNullOrEmpty(property.NHMColumnName)
                                ? property.Name
                                : property.NHMColumnName
                            ));
                        xml.WriteAttributeString("type", property.Type);

                        if (property.IsUnique)
                            xml.WriteAttributeString("unique", "true");

                        xml.WriteAttributeString("not-null", property.IsNotNull.ToString().ToLower());
                        xml.WriteEndElement();
                    }
                }

                xml.WriteEndElement();
                xml.WriteEndElement();
                xml.WriteEndDoreplacedent();
            }
        }

19 Source : USPSProvider.cs
with MIT License
from alexeybusygin

public async Task GetRates(bool baseRatesOnly)
        {
            // USPS only available for domestic addresses. International is a different API.
            if (!IsDomesticUSPSAvailable())
            {
                return;
            }

            var sb = new StringBuilder();
            var specialServices = GetSpecialServicesForShipment(Shipment);

            var settings = new XmlWriterSettings
            {
                Indent = false,
                OmitXmlDeclaration = true,
                NewLineHandling = NewLineHandling.None
            };

            using (var writer = XmlWriter.Create(sb, settings))
            {
                writer.WriteStartElement("RateV4Request");
                writer.WriteAttributeString("USERID", _userId);
                if (!baseRatesOnly)
                {
                    writer.WriteElementString("Revision", "2");
                }
                var i = 0;
                foreach (var package in Shipment.Packages)
                {
                    string size;
                    var container = package.Container;
                    if (IsPackageLarge(package))
                    {
                        size = "LARGE";
                        // Container must be RECTANGULAR or NONRECTANGULAR when SIZE is LARGE
                        if (container == null || container.ToUpperInvariant() != "NONRECTANGULAR")
                        {
                            container = "RECTANGULAR";
                        }
                    }
                    else
                    {
                        size = "REGULAR";
                        if (container == null)
                        {
                            container = string.Empty;
                        }
                    }

                    writer.WriteStartElement("Package");
                    writer.WriteAttributeString("ID", i.ToString());
                    writer.WriteElementString("Service", _service);
                    writer.WriteElementString("ZipOrigination", Shipment.OriginAddress.CountryCode == "US" && Shipment.OriginAddress.PostalCode.Length > 5? Shipment.OriginAddress.PostalCode.Substring(0, 5) : Shipment.OriginAddress.PostalCode);
                    writer.WriteElementString("ZipDestination", Shipment.DestinationAddress.CountryCode == "US" && Shipment.DestinationAddress.PostalCode.Length > 5 ? Shipment.DestinationAddress.PostalCode.Substring(0, 5) : Shipment.DestinationAddress.PostalCode);
                    writer.WriteElementString("Pounds", package.PoundsAndOunces.Pounds.ToString());
                    writer.WriteElementString("Ounces", package.PoundsAndOunces.Ounces.ToString());

                    writer.WriteElementString("Container", container);
                    writer.WriteElementString("Size", size);
                    writer.WriteElementString("Width", package.RoundedWidth.ToString());
                    writer.WriteElementString("Length", package.RoundedLength.ToString());
                    writer.WriteElementString("Height", package.RoundedHeight.ToString());
                    writer.WriteElementString("Girth", package.CalculatedGirth.ToString());
                    writer.WriteElementString("Value", package.InsuredValue.ToString());
                    if (RequiresMachinable(_service))
                    {
                        writer.WriteElementString("Machinable", IsPackageMachinable(package).ToString());
                    }
                    if (Shipment.Options.ShippingDate != null)
                    {
                        writer.WriteElementString("ShipDate",
                            Shipment.Options.ShippingDate.Value.ToString("yyyy-MM-dd"));
                    }

                    if (AllowsSpecialServices(_service) && specialServices.Any())
                    {
                        writer.WriteStartElement("SpecialServices");
                        foreach (var service in specialServices)
                        {
                            writer.WriteElementString("SpecialService", ((int)service).ToString());
                        }
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                    i++;
                }

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

            try
            {
                using (var httpClient = new HttpClient())
                {
                    var rateUri = new Uri($"{ProductionUrl}?API=RateV4&XML={sb}");
                    var response = await httpClient.GetStringAsync(rateUri).ConfigureAwait(false);

                    ParseResult(response, specialServices);
                }
            }
            catch (Exception ex)
            {
                AddInternalError($"USPS provider exception: {ex.Message}");
            }
        }

19 Source : DHLProvider.cs
with MIT License
from alexeybusygin

private static void WriteAddress(XmlWriter writer, string name, Address address)
        {
            writer.WriteStartElement(name);
            writer.WriteElementString("CountryCode",address.CountryCode);
            writer.WriteElementString("Postalcode", address.PostalCode);
            if (!string.IsNullOrWhiteSpace(address.City))
            {
                writer.WriteElementString("City", address.City);
            }
            writer.WriteEndElement(); // </From>
        }

19 Source : XmlWriterBase.cs
with MIT License
from AlexGyver

protected void WriteStartElement(string name)
        {
            this.w.WriteStartElement(name);
        }

19 Source : Settings.xaml.cs
with MIT License
from Alkl58

public void SaveSettingsTab()
        {
            try
            {
                if (!MainWindow.StartUp)
                {
                    XmlWriter writer = XmlWriter.Create(Path.Combine(Directory.GetCurrentDirectory(), "settings.xml"));
                    writer.WriteStartElement("Settings");
                    writer.WriteElementString("DeleteTempFiles", ToggleSwitchDeleteTempFiles.IsOn.ToString());
                    writer.WriteElementString("PlaySound", ToggleSwitchUISounds.IsOn.ToString());
                    writer.WriteElementString("Logging", ToggleSwitchLogging.IsOn.ToString());
                    writer.WriteElementString("ShowDialog", ToggleSwitchShowWindow.IsOn.ToString());
                    writer.WriteElementString("Shutdown", ToggleSwitchShutdownAfterEncode.IsOn.ToString());
                    writer.WriteElementString("TempPathActive", ToggleSwitchTempFolder.IsOn.ToString());
                    writer.WriteElementString("TempPath", TextBoxCustomTempPath.Text);
                    writer.WriteElementString("Terminal", ToggleSwitchHideTerminal.IsOn.ToString());
                    writer.WriteElementString("ThemeAccent", ComboBoxAccentTheme.SelectedIndex.ToString());
                    writer.WriteElementString("ThemeBase", ComboBoxBaseTheme.SelectedIndex.ToString());
                    writer.WriteElementString("BatchContainer", ComboBoxContainerBatchEncoding.SelectedIndex.ToString());
                    writer.WriteElementString("ReencodeMessage", MainWindow.reencodeMessage.ToString());
                    writer.WriteElementString("Language", ComboBoxUILanguage.Text ?? "English");
                    writer.WriteElementString("SkipSubreplacedles", ToggleSkipSubreplacedleExtraction.IsOn.ToString());
                    writer.WriteElementString("OverrideWorkerCount", ToggleOverrideWorkerCount.IsOn.ToString());
                    writer.WriteEndElement();
                    writer.Close();
                }
            }
            catch { }
        }

19 Source : SelfUpdateProgressPage.cs
with GNU General Public License v3.0
from Amebis

public override void OnActivate()
        {
            base.OnActivate();

            // Setup self-update.
            var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
            selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                selfUpdate.ReportProgress(0);
                var random = new Random();
                var tempFolder = Path.GetTempPath();
                var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
                Directory.CreateDirectory(workingFolder);
                try
                {
                    string installerFilename = null;
                    FileStream installerFile = null;

                    // Download installer.
                    while (DownloadUris.Count > 0)
                    {
                        Window.Abort.Token.ThrowIfCancellationRequested();
                        var uriIndex = random.Next(DownloadUris.Count);
                        try
                        {
                            var binaryUri = DownloadUris[uriIndex];
                            Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
                            var request = WebRequest.Create(binaryUri);
                            request.Proxy = null;
                            using (var response = request.GetResponse())
                            {
                                // 1. Get installer filename from Content-Disposition header.
                                // 2. Get installer filename from the last segment of URI path.
                                // 3. Fallback to a predefined installer filename.
                                try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
                                catch
                                {
                                    try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
                                    catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
                                }

                                // Save response data to file.
                                installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                                try
                                {
                                    using (var stream = response.GetResponseStream())
                                    {
                                        installerFile.Seek(0, SeekOrigin.Begin);
                                        var hash = new eduEd25519.SHA256();
                                        var buffer = new byte[1048576];
                                        long offset = 0, total = response.ContentLength;

                                        for (; ; )
                                        {
                                            // Wait for the data to arrive.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            var bufferLength = stream.Read(buffer, 0, buffer.Length);
                                            if (bufferLength == 0)
                                                break;
                                            //Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.

                                            // Append it to the file and hash it.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            installerFile.Write(buffer, 0, bufferLength);
                                            hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);

                                            // Report progress.
                                            offset += bufferLength;
                                            selfUpdate.ReportProgress((int)(offset * 100 / total));
                                        }

                                        hash.TransformFinalBlock(buffer, 0, 0);
                                        if (!hash.Hash.SequenceEqual(Hash))
                                            throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));

                                        installerFile.SetLength(installerFile.Position);
                                        break;
                                    }
                                }
                                catch
                                {
                                    // Close installer file.
                                    installerFile.Close();
                                    installerFile = null;

                                    // Delete installer file. If possible.
                                    Trace.TraceInformation("Deleting file {0}...", installerFilename);
                                    try { File.Delete(installerFilename); }
                                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
                                    installerFilename = null;

                                    throw;
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex)
                        {
                            Trace.TraceWarning("Error: {0}", ex.ToString());
                            DownloadUris.RemoveAt(uriIndex);
                        }
                    }

                    if (installerFilename == null || installerFile == null)
                    {
                        // The installer file is not ready.
                        throw new InstallerFileUnavailableException();
                    }

                    try
                    {
                        var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
                        var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                        try
                        {
                            // Prepare WSF file.
                            var writer = new XmlTextWriter(updaterFile, null);
                            writer.WriteStartDoreplacedent();
                            writer.WriteStartElement("package");
                            writer.WriteStartElement("job");

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "WScript.Shell");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "Scripting.FileSystemObject");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("script");
                            writer.WriteAttributeString("language", "JScript");
                            var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
                            var argv = Environment.GetCommandLineArgs();
                            var arguments = new StringBuilder();
                            for (long i = 1, n = argv.LongLength; i < n; i++)
                            {
                                if (i > 1) arguments.Append(" ");
                                arguments.Append("\"");
                                arguments.Append(argv[i].Replace("\"", "\"\""));
                                arguments.Append("\"");
                            }
                            var script = new StringBuilder();
                            script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
                            script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
                            script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
                            writer.WriteCData(script.ToString());
                            writer.WriteEndElement(); // script

                            writer.WriteEndElement(); // job
                            writer.WriteEndElement(); // package
                            writer.WriteEndDoreplacedent();
                            writer.Flush();

                            // Prepare WSF launch parameters.
                            Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
                            var process = new Process();
                            process.StartInfo.FileName = "wscript.exe";
                            process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
                            process.StartInfo.WorkingDirectory = workingFolder;

                            // Close WSF and installer files as late as possible to narrow the attack window.
                            // If Windows supported executing files that are locked for writing, we could leave those files open.
                            updaterFile.Close();
                            installerFile.Close();
                            process.Start();
                        }
                        catch
                        {
                            // Close WSF file.
                            updaterFile.Close();

                            // Delete WSF file. If possible.
                            Trace.TraceInformation("Deleting file {0}...", updaterFilename);
                            try { File.Delete(updaterFilename); }
                            catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }

                            throw;
                        }
                    }
                    catch
                    {
                        // Close installer file.
                        installerFile.Close();

                        // Delete installer file. If possible.
                        Trace.TraceInformation("Deleting file {0}...", installerFilename);
                        try { File.Delete(installerFilename); }
                        catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }

                        throw;
                    }
                }
                catch
                {
                    // Delete working folder. If possible.
                    try { Directory.Delete(workingFolder); }
                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }

                    throw;
                }
            };

            // Self-update progress.
            selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
            {
                Progress.Value = e.ProgressPercentage;
            };

            // Self-update complereplacedion.
            selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                if (e.Error == null)
                {
                    // Self-updating successfuly launched. Quit to release open files.
                    Wizard.OnQuitApplication(this);
                }
                else
                    Wizard.Error = e.Error;

                // Self-dispose.
                (sender as BackgroundWorker)?.Dispose();
            };

            selfUpdate.RunWorkerAsync();
        }

19 Source : AccessTokenDictionary.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var entry in this)
            {
                writer.WriteStartElement("AccessToken");
                writer.WriteAttributeString("Key", entry.Key);
                writer.WriteAttributeString("Value", entry.Value.ToBase64String());
                writer.WriteEndElement();
            }
        }

19 Source : Dictionary.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var entry in this)
            {
                writer.WriteStartElement(entry.Value.GetType().Name);
                writer.WriteAttributeString("Key", entry.Key);
                entry.Value.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

19 Source : LocalInstanceSourceSettings.cs
with GNU General Public License v3.0
from Amebis

public override void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement(nameof(InstanceRefList));
            writer.WriteAttributeString("Key", nameof(ConnectingInstanceList));
            ConnectingInstanceList.WriteXml(writer);
            writer.WriteEndElement();

            writer.WriteStartElement(nameof(InstanceSourceSettingsBase));
            base.WriteXml(writer);
            writer.WriteEndElement();
        }

19 Source : SerializableStringDictionary.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var entry in this)
            {
                writer.WriteStartElement("DictionaryEntry");
                writer.WriteAttributeString("Key", entry.Key);
                writer.WriteAttributeString("Value", entry.Value);
                writer.WriteEndElement();
            }
        }

19 Source : MinisignPublicKeyDictionary.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var el in this)
            {
                writer.WriteStartElement("PublicKey");
                using (var s = new MemoryStream(42))
                {
                    using (var w = new BinaryWriter(s))
                    {
                        w.Write('E');
                        w.Write('d');
                        w.Write(el.Key);
                        w.Write(el.Value);
                    }
                    writer.WriteBase64(s.GetBuffer(), 0, (int)s.Length);
                }
                writer.WriteEndElement();
            }
        }

19 Source : ResourceRef.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString(nameof(Uri), Uri.AbsoluteUri);

            if (PublicKeys != null)
            {
                writer.WriteStartElement(nameof(MinisignPublicKeyDictionary));
                writer.WriteAttributeString("Key", nameof(PublicKeys));
                PublicKeys.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

19 Source : UriList.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var el in this)
            {
                writer.WriteStartElement("Uri");
                writer.WriteAttributeString("AbsoluteUri", el.AbsoluteUri);
                writer.WriteEndElement();
            }
        }

19 Source : InstanceRef.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString(nameof(Base), Base.AbsoluteUri);
            writer.WriteAttributeString(nameof(Popularity), Popularity.ToString(CultureInfo.InvariantCulture));

            if (Profiles != null)
            {
                writer.WriteStartElement(nameof(ProfileRefList));
                writer.WriteAttributeString("Key", nameof(Profiles));
                Profiles.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

19 Source : InstanceRefList.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var el in this)
            {
                writer.WriteStartElement(nameof(InstanceRef));
                el.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

19 Source : InstanceSourceSettings.cs
with GNU General Public License v3.0
from Amebis

public virtual void WriteXml(XmlWriter writer)
        {
            if (InstanceSource != null)
            {
                writer.WriteStartElement(InstanceSource.GetType().Name);
                writer.WriteAttributeString("Key", nameof(InstanceSource));
                InstanceSource.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

19 Source : ProfileRefList.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var el in this)
            {
                writer.WriteStartElement(nameof(ProfileRef));
                el.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

19 Source : SvnItemAnnotation.cs
with Apache License 2.0
from AmpScm

public void Write(ISvnStatusCache context, XmlWriter to, string wcRoot)
        {
            to.WriteStartElement(ElemNode);
            to.WriteAttributeString(AttrName, new Uri(wcRoot).MakeRelativeUri(new Uri(wcRoot)).ToString());

            // TODO: Write explicit values

            if (_justStored != null)
                foreach (KeyValuePair<string, string> kv in _justStored)
                {
                    to.WriteAttributeString(kv.Key, kv.Value);
                }
            to.WriteEndElement();
        }

19 Source : ProjectView.cs
with MIT License
from AndresTraks

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dialog = new SaveFileDialog();
            dialog.FileName = Project.NamespaceName + ".xml";
            dialog.InitialDirectory = Project.FullProjectPath;
            dialog.Filter = "XML files|*.xml";
            var result = dialog.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }

            var settings = new XmlWriterSettings
            {
                Indent = true
            };
            using (var writer = XmlWriter.Create(dialog.FileName, settings))
            {
                writer.WriteStartElement("WrapperProject");
                writer.WriteStartElement("CppCodeModel");
                Project.WriteSourceItemXml(writer, Project.RootFolder, Path.GetDirectoryName(dialog.FileName) + Path.DirectorySeparatorChar);
            }
        }

19 Source : WrapperProject.cs
with MIT License
from AndresTraks

public void WriteSourceItemXml(XmlWriter writer, SourceItemDefinition item, string xmlFilePath = "")
        {
            string name = item.IsFolder
                ? ((item is RootFolderDefinition) ? "RootFolder" : "Folder")
                : "Header";

            writer.WriteStartElement(name);
            if (item == RootFolder)
            {
                writer.WriteAttributeString("Name", PathUtility.MakeRelativePath(xmlFilePath, item.Name));
            }
            else
            {
                writer.WriteAttributeString("Name", item.Name);
            }

            if (item.IsExcluded)
            {
                writer.WriteAttributeString("IsExcluded", "true");
            }

            if (!item.HasDefaultIncludeFolders)
            {
                WriteIncludeFolders(writer, item);
            }

            foreach (var child in item.Children)
            {
                WriteSourceItemXml(writer, child);
            }

            writer.WriteEndElement();
        }

19 Source : WrapperProject.cs
with MIT License
from AndresTraks

private void WriteIncludeFolders(XmlWriter writer, SourceItemDefinition item)
        {
            foreach (string includeFolder in item.IncludeFolders)
            {
                writer.WriteStartElement("IncludeFolder");
                writer.WriteString(includeFolder);
                writer.WriteEndElement();
            }
        }

19 Source : XmlLayout.cs
with Apache License 2.0
from apache

protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
		{
			writer.WriteStartElement(m_elmEvent);
			writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName);

#if NET_2_0 || NETCF_2_0 || MONO_2_0 || NETSTANDARD
			writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local));
#else
			writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp));
#endif

			writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName);
			writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName);

			if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0)
			{
				writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain);
			}
			if (loggingEvent.Idenreplacedy != null && loggingEvent.Idenreplacedy.Length > 0)
			{
				writer.WriteAttributeString(ATTR_IDENreplacedY, loggingEvent.Idenreplacedy);
			}
			if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0)
			{
				writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName);
			}
    
			// Append the message text
			writer.WriteStartElement(m_elmMessage);
			if (!this.Base64EncodeMessage)
			{
				Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement);
			}
			else
			{
				byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage);
				string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length);
				Transform.WriteEscapedXmlString(writer, base64Message,this.InvalidCharReplacement);
			}
			writer.WriteEndElement();

			PropertiesDictionary properties = loggingEvent.GetProperties();

			// Append the properties text
			if (properties.Count > 0)
			{
				writer.WriteStartElement(m_elmProperties);
				foreach(System.Collections.DictionaryEntry entry in properties)
				{
					writer.WriteStartElement(m_elmData);
					writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key,this.InvalidCharReplacement));

					// Use an ObjectRenderer to convert the object to a string
					string valueStr =null;
					if (!this.Base64EncodeProperties)
					{
						valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value),this.InvalidCharReplacement);
					}
					else
					{
						byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value));
						valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length);
					}
					writer.WriteAttributeString(ATTR_VALUE, valueStr);

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

			string exceptionStr = loggingEvent.GetExceptionString();
			if (exceptionStr != null && exceptionStr.Length > 0)
			{
				// Append the stack trace line
				writer.WriteStartElement(m_elmException);
				Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement);
				writer.WriteEndElement();
			}

			if (LocationInfo)
			{ 
				LocationInfo locationInfo = loggingEvent.LocationInformation;

				writer.WriteStartElement(m_elmLocation);
				writer.WriteAttributeString(ATTR_CLreplaced, locationInfo.ClreplacedName);
				writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName);
				writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName);
				writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber);
				writer.WriteEndElement();
			}

			writer.WriteEndElement();
		}

19 Source : Config.cs
with MIT License
from ASHTeam

public override void SetValue(string section, string entry, object value)
		{
			// If the value is null, remove the entry
			if (value == null)
			{
				RemoveEntry(section, entry);
				return;
			}

			VerifyNotReadOnly();
			VerifyName();
			VerifyAndAdjustSection(ref section);
			VerifyAndAdjustEntry(ref entry);

			if (!RaiseChangeEvent(true, ProfileChangeType.SetValue, section, entry, value))
				return;
			
			bool hasGroupName = HasGroupName;
			bool isAppSettings = IsAppSettings(section);
			
			// If the file does not exist, use the writer to quickly create it
			if ((m_buffer == null || m_buffer.IsEmpty) && !File.Exists(Name))
			{				
				XmlTextWriter writer = null;
				
				// If there's a buffer, write to it without creating the file
				if (m_buffer == null)
					writer = new XmlTextWriter(Name, Encoding);			
				else
					writer = new XmlTextWriter(new MemoryStream(), Encoding);			

				writer.Formatting = Formatting.Indented;
	            
	            writer.WriteStartDoreplacedent();
				
	            writer.WriteStartElement("configuration");			
				if (!isAppSettings)
				{
					writer.WriteStartElement("configSections");
					if (hasGroupName)
					{
						writer.WriteStartElement("sectionGroup");
						writer.WriteAttributeString("name", null, m_groupName);				
					}
					writer.WriteStartElement("section");
					writer.WriteAttributeString("name", null, section);				
					writer.WriteAttributeString("type", null, SECTION_TYPE);
        			writer.WriteEndElement();

					if (hasGroupName)
            			writer.WriteEndElement();
           			writer.WriteEndElement();
				}
				if (hasGroupName)
					writer.WriteStartElement(m_groupName);
				writer.WriteStartElement(section);
				writer.WriteStartElement("add");
				writer.WriteAttributeString("key", null, entry);				
				writer.WriteAttributeString("value", null, value.ToString());
    			writer.WriteEndElement();
    			writer.WriteEndElement();
				if (hasGroupName)
           			writer.WriteEndElement();
       			writer.WriteEndElement();
			
				if (m_buffer != null)
					m_buffer.Load(writer);
				writer.Close();   				

				RaiseChangeEvent(false, ProfileChangeType.SetValue, section, entry, value);
				return;
			}
			
			// The file exists, edit it
			
			XmlDoreplacedent doc = GetXmlDoreplacedent();
			XmlElement root = doc.DoreplacedentElement;
			
			XmlAttribute attribute = null;
			XmlNode sectionNode = null;
			
			// Check if we need to deal with the configSections element
			if (!isAppSettings)
			{
				// Get the configSections element and add it if it's not there
				XmlNode sectionsNode = root.SelectSingleNode("configSections");
				if (sectionsNode == null)
					sectionsNode = root.AppendChild(doc.CreateElement("configSections"));			
	
				XmlNode sectionGroupNode = sectionsNode;
				if (hasGroupName)
				{
					// Get the sectionGroup element and add it if it's not there
					sectionGroupNode = sectionsNode.SelectSingleNode("sectionGroup[@name=\"" + m_groupName + "\"]");
					if (sectionGroupNode == null)
					{
						XmlElement element = doc.CreateElement("sectionGroup");
						attribute = doc.CreateAttribute("name");
						attribute.Value = m_groupName;
						element.Attributes.Append(attribute);			
						sectionGroupNode = sectionsNode.AppendChild(element);			
					}
				}
	
				// Get the section element and add it if it's not there
				sectionNode = sectionGroupNode.SelectSingleNode("section[@name=\"" + section + "\"]");
				if (sectionNode == null)
				{
					XmlElement element = doc.CreateElement("section");
					attribute = doc.CreateAttribute("name");
					attribute.Value = section;
					element.Attributes.Append(attribute);			
	
					sectionNode = sectionGroupNode.AppendChild(element);			
				}
	
				// Update the type attribute
				attribute = doc.CreateAttribute("type");
				attribute.Value = SECTION_TYPE;
				sectionNode.Attributes.Append(attribute);			
			}

			// Get the element with the sectionGroup name and add it if it's not there
			XmlNode groupNode = root;
			if (hasGroupName)
			{
				groupNode = root.SelectSingleNode(m_groupName);
				if (groupNode == null)
					groupNode = root.AppendChild(doc.CreateElement(m_groupName));			
			}

			// Get the element with the section name and add it if it's not there
			sectionNode = groupNode.SelectSingleNode(section);
			if (sectionNode == null)
				sectionNode = groupNode.AppendChild(doc.CreateElement(section));			

			// Get the 'add' element and add it if it's not there
			XmlNode entryNode = sectionNode.SelectSingleNode("add[@key=\"" + entry + "\"]");
			if (entryNode == null)
			{
				XmlElement element = doc.CreateElement("add");
				attribute = doc.CreateAttribute("key");
				attribute.Value = entry;
				element.Attributes.Append(attribute);			

				entryNode = sectionNode.AppendChild(element);			
			}

			// Update the value attribute
			attribute = doc.CreateAttribute("value");
			attribute.Value = value.ToString();
			entryNode.Attributes.Append(attribute);			

			// Save the file
			Save(doc);
			RaiseChangeEvent(false, ProfileChangeType.SetValue, section, entry, value);
		}

19 Source : Xml.cs
with MIT License
from ASHTeam

public override void SetValue(string section, string entry, object value)
		{
			// If the value is null, remove the entry
			if (value == null)
			{
				RemoveEntry(section, entry);
				return;
			}
			
			VerifyNotReadOnly();
			VerifyName();
			VerifyAndAdjustSection(ref section);
			VerifyAndAdjustEntry(ref entry);

			if (!RaiseChangeEvent(true, ProfileChangeType.SetValue, section, entry, value))
				return;

			string valueString = value.ToString();

			// If the file does not exist, use the writer to quickly create it
			if ((m_buffer == null || m_buffer.IsEmpty) && !File.Exists(Name))
			{	
				XmlTextWriter writer = null;
				
				// If there's a buffer, write to it without creating the file
				if (m_buffer == null)
					writer = new XmlTextWriter(Name, Encoding);			
				else
					writer = new XmlTextWriter(new MemoryStream(), Encoding);			

				writer.Formatting = Formatting.Indented;
	            
	            writer.WriteStartDoreplacedent();
				
	            writer.WriteStartElement(m_rootName);			
					writer.WriteStartElement("section");
					writer.WriteAttributeString("name", null, section);				
						writer.WriteStartElement("entry");
						writer.WriteAttributeString("name", null, entry);				
	            			writer.WriteString(valueString);
	            		writer.WriteEndElement();
	            	writer.WriteEndElement();
	            writer.WriteEndElement();

				if (m_buffer != null)
					m_buffer.Load(writer);
				writer.Close();            							

				RaiseChangeEvent(false, ProfileChangeType.SetValue, section, entry, value);
				return;
			}
			
			// The file exists, edit it
			
			XmlDoreplacedent doc = GetXmlDoreplacedent();
			XmlElement root = doc.DoreplacedentElement;
			
			// Get the section element and add it if it's not there
			XmlNode sectionNode = root.SelectSingleNode(GetSectionsPath(section));
			if (sectionNode == null)
			{
				XmlElement element = doc.CreateElement("section");
				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
			XmlNode entryNode = sectionNode.SelectSingleNode(GetEntryPath(entry));
			if (entryNode == null)
			{
				XmlElement element = doc.CreateElement("entry");
				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 = valueString;
			Save(doc);		
			RaiseChangeEvent(false, ProfileChangeType.SetValue, section, entry, value);
		}

19 Source : FormatGenerator.cs
with Apache License 2.0
from aws

private void GenerateView_NonReflective(ConfigModel config, XmlWriter writer, Type targetType)
        {
            if (config.Columns.Count == 0) return;
            bool isTableView = config.Columns.Count <= 4;

            writer.WriteStartElement("View");
            {
                writer.WriteElementString("Name", string.Format("View node for {0}", targetType.FullName));

                writer.WriteStartElement("ViewSelectedBy");
                {
                    if (config.ApplicableTypes != null && config.ApplicableTypes.Count > 0)
                    {
                        foreach (var type in config.ApplicableTypes)
                        {
                            writer.WriteElementString("TypeName", type);
                        }
                    }
                    else
                    {
                        writer.WriteElementString("TypeName", targetType.FullName);
                    }
                }
                writer.WriteEndElement();

                writer.WriteStartElement(isTableView ? "TableControl" : "ListControl");
                {
                    if (isTableView)
                    {
                        writer.WriteStartElement("TableHeaders");
                        {
                            foreach (var header in config.Columns)
                            {
                                writer.WriteStartElement("TableColumnHeader");
                                {
                                    writer.WriteElementString("Label", header.HeaderLabel);
                                    if (header.HeaderWidth != 0)
                                        writer.WriteElementString("Width", header.HeaderWidth.ToString());
                                    if (header.HeaderAlignment != HeaderAlignment.None)
                                        writer.WriteElementString("Alignment", header.HeaderAlignment.ToString());
                                }
                                writer.WriteEndElement();
                            }
                        }
                        writer.WriteEndElement();
                    }

                    writer.WriteStartElement(isTableView ? "TableRowEntries" : "ListEntries");
                    {
                        writer.WriteStartElement(isTableView ? "TableRowEntry" : "ListEntry");
                        {
                            writer.WriteStartElement(isTableView ? "TableColumnItems" : "Lisreplacedems");
                            {
                                foreach (var column in config.Columns)
                                {
                                    writer.WriteStartElement(isTableView ? "TableColumnItem" : "Lisreplacedem");
                                    {
                                        if (!string.IsNullOrEmpty(column.PropertyName))
                                            writer.WriteElementString("PropertyName", column.PropertyName);
                                        else if (!string.IsNullOrEmpty(column.ScriptBlock))
                                            writer.WriteElementString("ScriptBlock", column.ScriptBlock);
                                        else
                                            throw new InvalidDataException("PropertyName and ScriptBlock are not set");
                                    }
                                    writer.WriteEndElement();
                                }
                            }
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }

19 Source : HelpGeneratorBase.cs
with Apache License 2.0
from aws

public static void WriteUnescapedElementString(this XmlWriter self, string localName, string value)
        {
            if (self == null) throw new ArgumentNullException("self");

            self.WriteStartElement(localName);
            var escapedString = EscapeString(value);
            self.WriteRaw(escapedString);
            self.WriteEndElement();
        }

19 Source : HelpGeneratorBase.cs
with Apache License 2.0
from aws

public static void WriteRawElementString(this XmlWriter self, string localName, string value)
        {
            if (self == null) throw new ArgumentNullException("self");

            self.WriteStartElement(localName);
            self.WriteRaw(value);
            self.WriteEndElement();
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

protected override void GenerateHelper()
        {
            Console.WriteLine("Generating Native PowerShell help (Get-Help) doreplacedentation file");
            base.GenerateHelper();

            var buildLogsPath = Path.Combine(this.Options.RootPath, "logs");
            if (!Directory.Exists(buildLogsPath))
                Directory.CreateDirectory(buildLogsPath);

            var logFilename = Path.Combine(buildLogsPath, Name + ".dll-Help.log");
            var oldWriter = Console.Out;
            try
            {
                using (var consoleWriter = new StreamWriter(File.OpenWrite(logFilename)))
                {
                    Console.SetOut(consoleWriter);
                    var outputFile = Path.Combine(this.OutputFolder, Name + PsHelpFilenameTail);

                    var settings = new XmlWriterSettings
                    {
                        Indent = true
                    };

                    using (var psHelpWriter = new XmlTextWriter(outputFile, Encoding.UTF8))
                    {
                        psHelpWriter.Formatting = Formatting.Indented;

                        psHelpWriter.WriteStartElement("helpItems");
                        psHelpWriter.WriteAttributeString("schema", "maml");

                        Parallel.ForEach(CmdletTypes, (cmdletType) =>
                        {
                            CmdletInfo cmdletInfo = InspectCmdletAttributes(cmdletType);

                            using (StringWriter sectionWriter = new StringWriter())
                            using (var sectionXmlWriter = XmlWriter.Create(sectionWriter, new XmlWriterSettings()
                            {
                                OmitXmlDeclaration = true,
                                ConformanceLevel = ConformanceLevel.Fragment,
                                CloseOutput = true
                            }))
                            {
                                string synopsis = null;
                                if (cmdletInfo.AWSCmdletAttribute == null)
                                {
                                    Console.WriteLine("Unable to find AWSCmdletAttribute for type " + cmdletType.FullName);
                                }
                                else
                                {
                                    var cmdletReturnAttributeType = cmdletInfo.AWSCmdletAttribute.GetType();
                                    synopsis = cmdletReturnAttributeType.GetProperty("Synopsis").GetValue(cmdletInfo.AWSCmdletAttribute, null) as string;
                                }

                                foreach (var cmdletAttribute in cmdletInfo.CmdletAttributes)
                                {
                                    sectionXmlWriter.WriteStartElement("command");
                                    sectionXmlWriter.WriteAttributeString("xmlns", "maml", null, "http://schemas.microsoft.com/maml/2004/10");
                                    sectionXmlWriter.WriteAttributeString("xmlns", "command", null, "http://schemas.microsoft.com/maml/dev/command/2004/10");
                                    sectionXmlWriter.WriteAttributeString("xmlns", "dev", null, "http://schemas.microsoft.com/maml/dev/2004/10");
                                    {
                                        var typeDoreplacedentation = DoreplacedentationUtils.GetTypeDoreplacedentation(cmdletType, replacedemblyDoreplacedentation);
                                        typeDoreplacedentation = DoreplacedentationUtils.FormatXMLForPowershell(typeDoreplacedentation);
                                        Console.WriteLine($"Cmdlet = {cmdletType.FullName}");
                                        Console.WriteLine($"Doreplacedentation = {typeDoreplacedentation}");

                                        var cmdletName = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName;

                                        var allProperties = GetRootSimpleProperties(cmdletType);
                                        var parameterParreplacedioning = new CmdletParameterSetParreplacedions(allProperties, cmdletAttribute.DefaultParameterSetName);

                                        var serviceAbbreviation = GetServiceAbbreviation(cmdletType);

                                        WriteDetails(sectionXmlWriter, cmdletAttribute, typeDoreplacedentation, cmdletName, synopsis);
                                        WriteSyntax(sectionXmlWriter, cmdletName, parameterParreplacedioning);
                                        WriteParameters(sectionXmlWriter, cmdletName, allProperties);
                                        WriteReturnValues(sectionXmlWriter, cmdletInfo.AWSCmdletOutputAttributes);
                                        WriteRelatedLinks(sectionXmlWriter, serviceAbbreviation, cmdletName);
                                        WriteExamples(sectionXmlWriter, cmdletName);
                                    }
                                    sectionXmlWriter.WriteEndElement();
                                }

                                sectionXmlWriter.Close();
                                lock (psHelpWriter)
                                {
                                    psHelpWriter.WriteRaw(sectionWriter.ToString());
                                }
                            }
                        });

                        psHelpWriter.WriteEndElement();
                    }

                    Console.WriteLine($"Verifying help file {outputFile} using XmlDoreplacedent...");
                    try
                    {
                        var doreplacedent = new XmlDoreplacedent();
                        doreplacedent.Load(outputFile);
                    }
                    catch (Exception e)
                    {
                        Logger.LogError(e, $"Error when loading file {outputFile} as XmlDoreplacedent");
                    }
                }
            }
            finally
            {
                Console.SetOut(oldWriter);
            }
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private static void WriteReturnValues(XmlWriter writer, IEnumerable<object> outputAttributes)
        {
            writer.WriteStartElement("returnValues");
            foreach (var outputAttribute in outputAttributes)
            {
                var attributeType = outputAttribute.GetType();
                writer.WriteStartElement("returnValue");
                {
                    writer.WriteStartElement("type");
                    {
                        var returnType = attributeType.GetProperty("ReturnType").GetValue(outputAttribute, null) as string;
                        writer.WriteElementString("name", returnType);
                        writer.WriteElementString("uri", string.Empty);
                        writer.WriteElementString("description", string.Empty);
                    }
                    writer.WriteEndElement();

                    writer.WriteStartElement("description");
                    writer.WriteStartElement("para");
                    {
                        var description = attributeType.GetProperty("Description").GetValue(outputAttribute, null) as string;
                        writer.WriteString(description);
                    }
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private static void WriteDetails(XmlWriter psHelpWriter, CmdletAttribute cmdletAttribute, string typeDoreplacedentation, string cmdletName, string synopsis)
        {
            psHelpWriter.WriteStartElement("details");
            {
                psHelpWriter.WriteElementString("name", cmdletName);
                psHelpWriter.WriteStartElement("description");
                {
                    if (string.IsNullOrEmpty(synopsis))
                    {
                        synopsis = string.Format("{0}-{1}", cmdletAttribute.VerbName, cmdletAttribute.NounName);
                    }
                    psHelpWriter.WriteUnescapedElementString("para", synopsis);
                }
                psHelpWriter.WriteEndElement();

                psHelpWriter.WriteElementString("verb", cmdletAttribute.VerbName);
                psHelpWriter.WriteElementString("noun", cmdletAttribute.NounName);
                psHelpWriter.WriteStartElement("copyright");
                {
                    psHelpWriter.WriteElementString("para",
                                                    string.Format("© Copyright 2012 - {0} Amazon.com, Inc.or its affiliates.All Rights Reserved.",
                                                                  DateTime.UtcNow.Year));
                }
                psHelpWriter.WriteEndElement();
            }
            psHelpWriter.WriteEndElement();

            psHelpWriter.WriteStartElement("description");
            {
                psHelpWriter.WriteUnescapedElementString("para", typeDoreplacedentation);
            }
            psHelpWriter.WriteEndElement();
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private static void WriteSyntax(XmlWriter writer, string cmdletName, CmdletParameterSetParreplacedions parameterSetParreplacedioning)
        {
            writer.WriteStartElement("syntax");
            if (parameterSetParreplacedioning.HasNamedParameterSets)
            {
                var sets = parameterSetParreplacedioning.NamedParameterSets;
                foreach (var set in sets)
                {
                    WriteSyntaxItem(writer, cmdletName, set, parameterSetParreplacedioning);
                }
            }
            else
            {
                WriteSyntaxItem(writer, cmdletName, CmdletParameterSetParreplacedions.AllSetsKey, parameterSetParreplacedioning);
            }
            writer.WriteEndElement();
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private static void WriteSyntaxItem(XmlWriter writer, string cmdletName, string setName, CmdletParameterSetParreplacedions parameterSetParreplacedioning)
        {
            var isCustomNamedSet = !setName.Equals(CmdletParameterSetParreplacedions.AllSetsKey);
            var isDefaultSet = isCustomNamedSet && setName.Equals(parameterSetParreplacedioning.DefaultParameterSetName, StringComparison.Ordinal);
            var setParameterNames = parameterSetParreplacedioning.ParameterNamesForSet(setName, parameterSetParreplacedioning.HasNamedParameterSets);

            writer.WriteStartElement("syntaxItem");
            {
                writer.WriteElementString("name", cmdletName);

                var allParameters = parameterSetParreplacedioning.Parameters;
                // Microsoft cmdlets show params in syntax in defined but non-alpha order. Use the ordering we found
                // during reflection here in the hope the sdk has them in 'most important' order
                foreach (var parameter in allParameters)
                {
                    if (!setParameterNames.Contains(parameter.CmdletParameterName))
                        continue;

                    InspectParameter(parameter, out var isRequiredForParametersets, out var pipelineInput, out var position, out var aliases);
                    var isRequiredForCurrentParameterset = isRequiredForParametersets != null && (isRequiredForParametersets.Count == 0 || isRequiredForParametersets.Contains(setName));

                    writer.WriteStartElement("parameter");
                    {
                        writer.WriteAttributeString("required", isRequiredForCurrentParameterset.ToString());
                        writer.WriteAttributeString("variableLength", "false");
                        writer.WriteAttributeString("globbing", "false");
                        writer.WriteAttributeString("pipelineInput", pipelineInput);
                        writer.WriteAttributeString("position", position);

                        writer.WriteElementString("name", parameter.CmdletParameterName);
                        writer.WriteStartElement("description");
                        {
                            writer.WriteRawElementString("para", parameter.PowershellDoreplacedentation);
                        }
                        writer.WriteEndElement();

                        writer.WriteStartElement("parameterValue");
                        {
                            writer.WriteAttributeString("required", "true");
                            writer.WriteAttributeString("variableLength", "false");
                            writer.WriteString(parameter.PropertyTypeName);
                        }
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private static void WriteParameters(XmlWriter writer, string cmdletName, IEnumerable<SimplePropertyInfo> allProperties)
        {
            writer.WriteStartElement("parameters");
            {
                // Microsoft cmdlets list the parameters in alpha order here, so do the same (leaving metadata/paging
                // params in the correct order)
                foreach (var property in allProperties.OrderBy(p => p.Name))
                {
                    writer.WriteStartElement("parameter");
                    {
                        InspectParameter(property, out var isRequiredForParametersets, out var pipelineInput, out var position, out var aliases);
                        var isRequiredForCurrentParameterset = isRequiredForParametersets?.Count == 0;

                        writer.WriteAttributeString("required", isRequiredForCurrentParameterset.ToString());
                        writer.WriteAttributeString("variableLength", "false");
                        writer.WriteAttributeString("globbing", "false");
                        writer.WriteAttributeString("pipelineInput", pipelineInput);
                        writer.WriteAttributeString("position", position);

                        writer.WriteElementString("name", property.Name);
                        writer.WriteStartElement("description");
                        {
                            writer.WriteRawElementString("para", property.PowershellDoreplacedentation);
                        }
                        writer.WriteEndElement();

                        writer.WriteStartElement("parameterValue");
                        {
                            writer.WriteAttributeString("required", "true");
                            writer.WriteAttributeString("variableLength", "false");
                            writer.WriteString(property.PropertyTypeName);
                        }
                        writer.WriteEndElement();

                        writer.WriteStartElement("type");
                        {
                            writer.WriteElementString("name", property.PropertyTypeName);
                            writer.WriteElementString("uri", string.Empty);
                        }
                        writer.WriteEndElement();

                        writer.WriteElementString("defaultValue", "None");
                    }
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();
        }

19 Source : FormatGenerator.cs
with Apache License 2.0
from aws

protected override void GenerateHelper()
        {
            var configurationsFolder = Path.Combine(Options.RootPath, FormatGeneratorConfigurationsFoldername);
            ConfigCollection = ConfigModelCollection.LoadAllConfigs(configurationsFolder, Options.Verbose);

            LoadCustomFormatDoreplacedents(configurationsFolder);

            var types = new List<Type>();
            foreach (var replacedembly in Targetreplacedemblies)
            {
                var replacedemblyTypes = GetTypes(replacedembly);
                types.AddRange(replacedemblyTypes);

                var includeTypes = GetTypes(replacedembly, ConfigCollection.TypesToInclude.ToArray());
                types.AddRange(includeTypes);
            }

            var cmdletType = typeof(Cmdlet);
            types.RemoveAll(t =>
            {
                var isPrivate = !t.IsPublic || t.IsNestedPrivate;
                var shouldExclude = ConfigCollection.TypeExclusionSet.Contains(t.FullName);
                var isCmdlet = t.IsSubclreplacedOf(cmdletType);

                var exclude = (isPrivate || shouldExclude || isCmdlet);
                if (exclude)
                    Logger.Log("Excluding type {0} from formats file", t.FullName);

                return exclude;
            });

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

            var outputFile = Path.Combine(OutputFolder, Name + ".Format.ps1xml");
            if (File.Exists(outputFile))
                File.Delete(outputFile);

            using (var stream = File.OpenWrite(outputFile))
            {
                var writerSettings = new XmlWriterSettings
                {
                    Encoding = Encoding.UTF8,
                    Indent = true
                };
                using (var writer = XmlWriter.Create(stream, writerSettings))
                {
                    writer.WriteStartDoreplacedent();
                    writer.WriteStartElement("Configuration");
                    writer.WriteStartElement("ViewDefinitions");

                    foreach (var type in types)
                    {
                        var config = GetConfig(type);

                        Logger.Log();
                        Logger.Log(new string('>', 20));
                        Logger.Log("Generating config: {0}", config);

                        GenerateView(config, writer, type);

                        Logger.Log(new string('<', 20));
                        Logger.Log();
                    }

                    foreach (var cfd in ConfigCollection.CustomFormatDoreplacedents)
                    {
                        var viewDefinitions = cfd.SelectSingleNode("descendant::ViewDefinitions");
                        if (viewDefinitions == null)
                            continue;

                        foreach (var viewNode in viewDefinitions.ChildNodes)
                        {
                            var viewNodeXml = viewNode as XmlNode;
                            using (var reader = XmlReader.Create(new StringReader(viewNodeXml.OuterXml)))
                            {
                                writer.WriteNode(reader, false);
                            }
                        }
                    }

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

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private void WriteRelatedLinks(XmlWriter writer, string serviceAbbreviation, string cmdletName)
        {
            var webrefLink 
                = string.Format("{0}/index.html?page={1}.html&tocid={1}",
                                WebApiReferenceBaseUrl,
                                cmdletName);

            writer.WriteStartElement("relatedLinks");

            // first link must always be to the online version so get-help -online works
            WriteRelatedHelpNavigationLink(writer, "Online version:", webrefLink);

            WriteRelatedHelpNavigationLink(writer,
                                            "Common credential and region parameters: ",
                                            string.Format("{0}/items/pstoolsref-commonparams.html", WebApiReferenceBaseUrl));

            // finish with any service api reference/user guide links
            XmlDoreplacedent doreplacedent;
            if (LinksCache.TryGetValue(serviceAbbreviation, out doreplacedent))
            {
                ConstructLinks(writer, doreplacedent, "*");
                ConstructLinks(writer, doreplacedent, cmdletName);
            }

            writer.WriteEndElement();
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private static void WriteRelatedHelpNavigationLink(XmlWriter writer, string linkText, string linkUri)
        {
            writer.WriteStartElement("navigationLink");
            {
                writer.WriteElementString("linkText", linkText);
                writer.WriteElementString("uri", string.IsNullOrEmpty(linkUri) ? string.Empty : linkUri);
            }
            writer.WriteEndElement();
        }

19 Source : PSHelpGenerator.cs
with Apache License 2.0
from aws

private void WriteExamples(XmlWriter writer, string cmdletName)
        {
            XmlDoreplacedent doreplacedent;
            if (!ExamplesCache.TryGetValue(cmdletName, out doreplacedent))
            {
                Console.WriteLine("NO EXAMPLES - {0}", cmdletName);
                return;
            }

            var set = doreplacedent.SelectSingleNode("examples");
            if (set == null || !set.HasChildNodes)
            {
                Console.WriteLine("NO EXAMPLES - {0} (file present but empty)", cmdletName);
                return;
            }

            writer.WriteStartElement("examples");
            {
                int exampleIndex = 1;
                var examples = set.SelectNodes("example");
                foreach (XmlNode example in examples)
                {
                    writer.WriteStartElement("example");
                    {
                        writer.WriteElementString("replacedle", string.Format(examplereplacedleFormat, exampleIndex));
                        {
                            // code tag CANNOT HAVE PARA TAGS
                            var code = example.SelectSingleNode("code");
                            if (code == null)
                            {
                                Logger.LogError("Unable to find examples <code> tag for cmdlet " + cmdletName);
                            }
                            
                            writer.WriteRawElementString("code", code.InnerXml);

                            // remarks tag MUST HAVE PARA TAGS
                            var description = example.SelectSingleNode("description");
                            if (description == null)
                            {
                                Logger.LogError("Unable to find examples <description> tag for cmdlet " + cmdletName);
                            }
                            var correctedText = DoreplacedentationUtils.ProcessLines(description.InnerXml, s => string.Format("<para>{0}</para>", s));
                            // we use br/ tags to format the description for webhelp, for native help we can replace
                            // with simple newlines
                            correctedText = correctedText.Replace("<br />", "\n"); // xml handler shows us <br/> as <br />
                            // <url>link</url> elements are stripped to leave the inner link text for the user to copy/paste
                            // (web help converts these to <a href="link" />)
                            correctedText = correctedText.Replace("<url>", "");
                            correctedText = correctedText.Replace("</url>", "");
                            var remarks = string.Format(remarksFormat, correctedText);
                            writer.WriteUnescapedElementString("remarks", remarks);
                        }
                    }
                    writer.WriteEndElement();
                    exampleIndex++;
                }
            }
            writer.WriteEndElement();
        }

19 Source : XmlReportWriter.cs
with Apache License 2.0
from aws

public static void SerializeReport(string folderPath, IEnumerable<ConfigModel> models)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            var overrides = XmlOverridesMerger.GetOverridesDescription(folderPath, out var errorMessage);

            var filename = Path.Combine(folderPath, "report.xml");
            try
            {
                var writerSettings = new XmlWriterSettings
                {
                    Encoding = new UTF8Encoding(false),
                    Indent = true,
                    IndentChars = "    "
                };

                //We only include services with errors, new operations or operations requiring a configuration update
                var configModelsToOutput = models.Where(configModel =>
                        configModel.replacedysisErrors.Any() ||
                        overrides.ContainsKey(configModel.C2jFilename) ||
                        configModel.ServiceOperationsList.Where(op => op.IsAutoConfiguring || op.replacedysisErrors.Any()).Any())
                    .ToArray();

                var doc = new XDoreplacedent();

                using (var writer = doc.CreateWriter())
                {
                    writer.WriteStartElement("Overrides");
                    writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
                    writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                    writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "https://raw.githubusercontent.com/aws/aws-tools-for-powershell/master/XmlSchemas/ConfigurationOverrides/overrides.xsd");

                    if (errorMessage != null)
                    {
                        writer.WriteComment($"ERROR - {errorMessage}");
                    }

                    foreach (var configModel in configModelsToOutput)
                    {
                        var xmlAttributeOverrides = new XmlAttributeOverrides();
                        xmlAttributeOverrides.Add(typeof(ConfigModel), new XmlAttributes() { XmlRoot = new XmlRootAttribute("Service") });
                        var serializer = new XmlSerializer(typeof(ConfigModel), xmlAttributeOverrides);
                        serializer.Serialize(writer, configModel);
                    }

                    writer.WriteEndElement(); //Overrides
                }

                foreach (var configModel in doc.Root.Elements().Zip(configModelsToOutput, (element, model) => (element, model)))
                {
                    List<XComment> serviceComments = new List<XComment>();

                    XmlOverridesMerger.OverrideDescription modelOverrides;
                    if (overrides.TryGetValue(configModel.model.C2jFilename, out modelOverrides) && modelOverrides.FileVersion != configModel.model.FileVersion)
                    {
                        replacedysisError.WrongFileVersionNumber(configModel.model);
                        modelOverrides = null;
                    }

                    serviceComments.Add(new XComment($"The current full configuration for this service is available at https://raw.githubusercontent.com/aws/aws-tools-for-powershell/master/generator/AWSPSGeneratorLib/Config/ServiceConfig/{configModel.model.C2jFilename}.xml."));

                    foreach (var error in configModel.model.replacedysisErrors)
                    {
                        serviceComments.Add(new XComment($"ERROR - {error.Message}"));
                    }

                    foreach (var serviceElement in configModel.element.Elements().ToArray())
                    {
                        switch (serviceElement.Name.LocalName)
                        {
                            case nameof(ConfigModel.C2jFilename):
                            case nameof(ConfigModel.ServiceOperations):
                            case nameof(ConfigModel.FileVersion):
                                //Preserve these elements
                                break;
                            case nameof(ConfigModel.SkipCmdletGeneration):
                            case nameof(ConfigModel.replacedemblyName):
                            case nameof(ConfigModel.ServiceNounPrefix):
                            case nameof(ConfigModel.ServiceName):
                            case nameof(ConfigModel.ServiceClientInterface):
                            case nameof(ConfigModel.ServiceClient):
                            case nameof(ConfigModel.ServiceModuleGuid):
                                //Remove unless present in the override file
                                if (!(modelOverrides?.ElementNames.Contains(serviceElement.Name.LocalName) ?? false))
                                {
                                    serviceElement.Remove();
                                }
                                break;
                            default:
                                //Change into comments unless present in the override file
                                if (!(modelOverrides?.ElementNames.Contains(serviceElement.Name.LocalName) ?? false))
                                {
                                    serviceComments.Add(new XComment(serviceElement.ToString()));
                                    serviceElement.Remove();
                                }
                                break;
                        }
                    }

                    var serviceOperationsElement = configModel.element.Element("ServiceOperations");

                    serviceOperationsElement.AddBeforeSelf(serviceComments);

                    var operations = serviceOperationsElement.Elements()
                        .Join(configModel.model.ServiceOperationsList, element => element.Attribute("MethodName").Value, operation => operation.MethodName, (element, operation) => (element, operation))
                        .ToArray();

                    foreach (var operation in operations)
                    {
                        var isConfigurationOverridden = modelOverrides?.MethodNames.Contains(operation.operation.MethodName) ?? false;

                        //We only include in the report new operations (IsAutoConfiguring=true) and operations requiring configuration updated. We also retain in the report
                        //any operation that was manually configured.
                        if (operation.operation.IsAutoConfiguring ||
                            operation.operation.replacedysisErrors.Any() ||
                            isConfigurationOverridden)
                        {
                            var firstOperationChildElement = operation.element.Elements().FirstOrDefault();

                            if (operation.operation.IsAutoConfiguring)
                            {
                                operation.element.AddFirst(new XComment($"INFO - This is a new cmdlet."));
                            }
                            if (isConfigurationOverridden)
                            {
                                operation.element.AddFirst(new XComment($"INFO - The configuration of this cmdlet is being changed through overrides."));
                            }
                            foreach (var error in operation.operation.replacedysisErrors)
                            {
                                operation.element.AddFirst(new XComment($"ERROR - {error.Message}"));
                            }

                            try
                            {
                                //Excluded operations have replacedyzer == null
                                if (operation.operation.replacedyzer != null)
                                {
                                    if (operation.operation.replacedyzer.replacedyzedParameters.Any())
                                    {
                                        var parametersComments = operation.operation.replacedyzer.replacedyzedParameters.Select(PropertyChangedEventArgs => GetParameterCommentForReport(PropertyChangedEventArgs, operation.operation.replacedyzer));
                                        operation.element.Add(new XComment($"INFO - Parameters:\n            {string.Join(";\n            ", parametersComments)}."));
                                    }

                                    var returnTypeComment = GetReturnTypeComment(operation.operation.replacedyzer);
                                    if (returnTypeComment != null)
                                    {
                                        operation.element.Add(new XComment($"INFO - {returnTypeComment}"));
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                operation.element.AddFirst(new XComment($"ERROR - Exception while generating operation report: {e.ToString()}"));
                            }
                        }
                        else
                        {
                            operation.element.Remove();
                        }
                    }
                }

                doc.Save(filename);
            }
            catch (Exception e)
            {
                throw new IOException("Unable to serialize report to " + filename, e);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                throw new Exception(errorMessage);
            }
        }

19 Source : SerializableDictionary.cs
with Apache License 2.0
from aws

public void WriteXml(XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

            foreach (TKey key in this.Keys)
            {
                writer.WriteStartElement("item");

                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();

                writer.WriteStartElement("value");
                TValue value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
        }

19 Source : IndexXmlRenderer.cs
with MIT License
from barry-jones

public override void Render(XmlWriter writer)
        {
            writer.WriteStartDoreplacedent();
            writer.WriteStartElement("index");

            foreach (Entry current in this.doreplacedentMap)
            {
                writer.WriteStartElement("item");
                writer.WriteAttributeString("name", current.Name);
                writer.WriteAttributeString("safename", Exporter.CreateSafeName(current.Name));
                writer.WriteAttributeString("key", current.Key.ToString());
                writer.WriteAttributeString("subkey", current.SubKey);

                foreach (Entry child in current.Children)
                {
                    this.Render(child, writer);
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement(); // index
            writer.WriteEndDoreplacedent();
        }

See More Examples