public void SendData() { string data; data = "Data#"; using (var sw = new StringWriterWithEncoding(Encoding.UTF8)) { using (var xw = XmlWriter.Create(sw, new XmlWriterSettings() { Indent = true,CheckCharacters=true,OmitXmlDeclaration=true, Encoding = Encoding.UTF8 })) { // Build Xml with xw. values.Export(xw); } data+= sw.ToString(); } data += "\n"; try { client.Send(data); }catch { } //textBox1.Text = data; //client.Send(data); }
private static async Task <string> BuildAtomFeed( DateTimeOffset lastFeedUpdate, PagedQueryable <StreetNameSyndicationQueryResult> pagedStreetNames, IOptions <ResponseOptions> responseOptions, IConfiguration configuration) { var sw = new StringWriterWithEncoding(Encoding.UTF8); using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings { Async = true, Indent = true, Encoding = sw.Encoding })) { var formatter = new AtomFormatter(null, xmlWriter.Settings) { UseCDATA = true }; var writer = new AtomFeedWriter(xmlWriter, null, formatter); var syndicationConfiguration = configuration.GetSection("Syndication"); var atomFeedConfig = AtomFeedConfigurationBuilder.CreateFrom(syndicationConfiguration, lastFeedUpdate); await writer.WriteDefaultMetadata(atomFeedConfig); var streetNames = pagedStreetNames.Items.ToList(); var nextFrom = streetNames.Any() ? streetNames.Max(s => s.Position) + 1 : (long?)null; var nextUri = BuildNextSyncUri(pagedStreetNames.PaginationInfo.Limit, nextFrom, syndicationConfiguration["NextUri"]); if (nextUri != null) { await writer.Write(new SyndicationLink(nextUri, GrArAtomLinkTypes.Next)); } foreach (var streetName in streetNames) { await writer.WriteStreetName(responseOptions, formatter, syndicationConfiguration["Category"], streetName); } xmlWriter.Flush(); } return(sw.ToString()); }
/// <summary> /// Builds sitemap structure /// </summary> /// <param name="sitemapSiteConfiguration">Sitemap site configuration</param> /// <returns>Sitemap content</returns> public virtual String BuildSitemap(SitemapSiteConfiguration sitemapSiteConfiguration) { var result = String.Empty; var options = GetUrlOptions(); var encoding = Encoding.UTF8; StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(encoding); // - Creating the XML Header - var xml = new XmlTextWriter(stringWriter); xml.WriteStartDocument(); xml.WriteStartElement("urlset", DynamicSitemapConfiguration.XmlnsTpl); try { options.Site = sitemapSiteConfiguration.Site; options.Language = sitemapSiteConfiguration.Language; List <Item> items = GetItems(sitemapSiteConfiguration.Site.RootPath, sitemapSiteConfiguration.Language); ProcessItems(items, sitemapSiteConfiguration, options, xml); } catch (Exception exc) { Sitecore.Diagnostics.Log.Error(String.Format(Messages.ExceptionWhileBuilding, sitemapSiteConfiguration.Site.Name, exc.Message, exc.StackTrace), this); } finally { xml.WriteEndElement(); xml.WriteEndDocument(); xml.Flush(); result = stringWriter.ToString(); Sitecore.Diagnostics.Log.Info(String.Format(Messages.SitemapBuildSuccess, sitemapSiteConfiguration), this); } return(result); }
public static string ToXmlString <T>(this T value, bool removeDefaultXmlNamespaces = true, bool omitXmlDeclaration = true, Encoding encoding = null) where T : class { XmlSerializerNamespaces namespaces = removeDefaultXmlNamespaces ? new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }) : null; XmlWriterSettings settings = new XmlWriterSettings { Indent = false, OmitXmlDeclaration = omitXmlDeclaration, CheckCharacters = false }; using (StringWriterWithEncoding stream = new StringWriterWithEncoding(encoding)) using (XmlWriter writer = XmlWriter.Create(stream, settings)) { var serializer = new XmlSerializer(value.GetType()); serializer.Serialize(writer, value, namespaces); return(stream.ToString()); } }
public async Task WritePerson() { var sw = new StringWriterWithEncoding(Encoding.UTF8); using (var xmlWriter = XmlWriter.Create(sw)) { var writer = new RssFeedWriter(xmlWriter); await writer.Write(new SyndicationPerson("John Doe", "*****@*****.**")); await writer.Write(new SyndicationPerson("John Smith", "*****@*****.**", RssContributorTypes.ManagingEditor)); await writer.Flush(); } string res = sw.ToString(); Assert.True(res == "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><author>[email protected] (John Doe)</author><managingEditor>[email protected] (John Smith)</managingEditor></channel></rss>"); }
public static string Serialize(CommandModel model) { var settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\n", OmitXmlDeclaration = false, Encoding = Encoding.UTF8, }; using (var buffer = new StringWriterWithEncoding(Encoding.UTF8)) using (var xmlWriter = XmlWriter.Create(buffer, settings)) { SerializeModel(model).WriteTo(xmlWriter); xmlWriter.Flush(); return(buffer.GetStringBuilder().ToString()); } }
internal static string ObtenerXMLComoString <T>(T documento) { XmlSerializer vloSerializador = new XmlSerializer(typeof(T)); XmlWriterSettings vloConfiguraciones = new XmlWriterSettings(); vloConfiguraciones.Encoding = new UnicodeEncoding(false, false); vloConfiguraciones.Indent = true; vloConfiguraciones.OmitXmlDeclaration = false; //modificado por JLEG using (StringWriter vloEscritor = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(vloEscritor, vloConfiguraciones)) { vloSerializador.Serialize(xmlWriter, documento); } return(vloEscritor.ToString()); } }
public static string ToXml(this XDocument document) { Encoding encoding; try { encoding = Encoding.GetEncoding(document.Declaration.Encoding); } catch { encoding = Encoding.UTF8; } using (var writer = new StringWriterWithEncoding(encoding)) { document.Save(writer); writer.Flush(); return(writer.ToString()); } }
public void OnSalvarAdicaoCommand() { try { HabilitaEdicao = false; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ClasseEmpresasAnexos)); ObservableCollection <ClasseEmpresasAnexos.EmpresaAnexo> _EmpresasAnexosPro = new ObservableCollection <ClasseEmpresasAnexos.EmpresaAnexo>(); ClasseEmpresasAnexos _ClasseEmpresasAnexosPro = new ClasseEmpresasAnexos(); _EmpresasAnexosPro.Add(AnexoSelecionado); _ClasseEmpresasAnexosPro.EmpresasAnexos = _EmpresasAnexosPro; string xmlString; using (StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.UTF8)) { using (XmlTextWriter xw = new XmlTextWriter(sw)) { xw.Formatting = Formatting.Indented; serializer.Serialize(xw, _ClasseEmpresasAnexosPro); xmlString = sw.ToString(); } } InsereAnexoBD(xmlString); int _empresaID = AnexoSelecionado.EmpresaID; Thread CarregaColecaoAnexos_thr = new Thread(() => CarregaColecaoAnexos(_empresaID)); CarregaColecaoAnexos_thr.Start(); _AnexosTemp.Add(AnexoSelecionado); Anexos = null; Anexos = new ObservableCollection <ClasseEmpresasAnexos.EmpresaAnexo>(_AnexosTemp); SelectedIndex = _selectedIndexTemp; _AnexosTemp.Clear(); _ClasseEmpresasAnexosPro = null; _AnexosTemp.Clear(); _anexoTemp = null; } catch (Exception ex) { } }
public static string ToXmlString <T>(T rootElement, bool indent = true) { var serializer = new XmlSerializer(typeof(T)); // no xmlns adding // see: https://stackoverflow.com/a/8882612 var xmlNamespaces = new XmlSerializerNamespaces(); xmlNamespaces.Add("", ""); var stringWriter = new StringWriterWithEncoding(Encoding.UTF8); var xmlWriterSettings = new XmlWriterSettings { Indent = indent }; using var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings); serializer.Serialize(xmlWriter, rootElement, xmlNamespaces); return(stringWriter.ToString()); }
public static string SerializeObject( this System.Xml.Serialization.XmlSerializer serializer, object instance, Encoding encoding, Formatting formatting, ISerializeOptions options) { var sb = new StringBuilder(); using (var stringWriter = new StringWriterWithEncoding(sb, encoding ?? Encoding.UTF8)) { using (var xmlWriter = new XSerializerXmlTextWriter(stringWriter, options)) { xmlWriter.Formatting = formatting; serializer.Serialize(xmlWriter, instance, options.Namespaces); } } return(sb.ToString()); }
public static string Serialize(object source, Encoding encodingOverride, string defaultNamespace = null) { if (source == null) { throw new ArgumentNullException("source"); } // Serialize Type objectType = source.GetType(); XmlSerializer serializer = new XmlSerializer(objectType, defaultNamespace); StringBuilder sb = new StringBuilder(); using (StringWriterWithEncoding strWriter = new StringWriterWithEncoding(sb, encodingOverride)) { serializer.Serialize(strWriter, source); } return(sb.ToString()); }
private void xuatWord() { HtmlForm form = new HtmlForm(); string filename = DateTime.Now.ToString("yyyy.MM.dd.hh.mm.ss") + ".doc"; string attachment = "attachment; filename=" + filename; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-word"; StringWriterWithEncoding stringWrite = new StringWriterWithEncoding(Encoding.UTF8); HtmlTextWriter htw = new HtmlTextWriter(stringWrite); Table1.RenderControl(htw); Response.Charset = "UTF-8"; Response.ContentEncoding = Encoding.UTF8; Response.Write(stringWrite.ToString()); Response.End(); //logDuLieu(filename, Convert.ToString(Request.QueryString["QuanLyDeThi_MaDT"])); }
public static string SerializeObject( this System.Xml.Serialization.XmlSerializer serializer, object instance, Encoding encoding, Formatting formatting, ISerializeOptions options) { var sb = new StringBuilder(); using (var stringWriter = new StringWriterWithEncoding(sb, encoding ?? Encoding.UTF8)) { using (var xmlWriter = new XSerializerXmlTextWriter(stringWriter, options)) { xmlWriter.Formatting = formatting; serializer.Serialize(xmlWriter, instance, options.Namespaces); } } return sb.ToString(); }
public async Task WriteNamespaces() { var sw = new StringWriterWithEncoding(Encoding.UTF8); using (XmlWriter xmlWriter = XmlWriter.Create(sw)) { var writer = new RssFeedWriter(xmlWriter, new SyndicationAttribute[] { new SyndicationAttribute("xmlns:content", "http://contoso.com/") }); await writer.Write(new SyndicationContent("hello", "http://contoso.com/", "world")); await writer.Write(new SyndicationContent("world", "http://contoso.com/", "hello")); await writer.Flush(); } string res = sw.ToString(); Assert.True(res == "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss xmlns:content=\"http://contoso.com/\" version=\"2.0\"><channel><content:hello>world</content:hello><content:world>hello</content:world></channel></rss>"); }
private string BuildXml(Node e, bool indent) { if (e != null) { var w = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = indent, IndentChars = " " }; using (var sr = new StringWriterWithEncoding(Encoding.UTF8)) { using (var xw = XmlWriter.Create(sr, w)) WriteTree(this, xw, null); sr.Flush(); return(sr.ToString()); } } return(""); }
string XmlSerialize(SaveData proxies) { CreateXmlSerializer(); var str = ""; using (var textWriter = new StringWriterWithEncoding(new StringBuilder(), new System.Text.ASCIIEncoding())) { using (XmlTextWriter xmlWriter = new XmlTextWriter(textWriter)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 4; m_CachedXmlSerializer.Serialize(xmlWriter, proxies); } str = textWriter.ToString(); } return(str); }
protected static string CreateResultDocument(DvAction action, IList <OutParameter> outParameters, bool forceSimpleValues) { StringBuilder result = new StringBuilder(2000); using (StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(result, UPnPConsts.UTF8_NO_BOM)) using (XmlWriter writer = XmlWriter.Create(stringWriter, UPnPConfiguration.DEFAULT_XML_WRITER_SETTINGS)) { SoapHelper.WriteSoapEnvelopeStart(writer, true); writer.WriteStartElement("u", action.Name + "Response", action.ParentService.ServiceTypeVersion_URN); foreach (OutParameter parameter in outParameters) { writer.WriteStartElement(parameter.Argument.Name); parameter.Argument.SoapSerializeArgument(parameter.Value, forceSimpleValues, writer); writer.WriteEndElement(); // parameter.Argument.Name } writer.WriteEndElement(); // u:[action.Name]Response SoapHelper.WriteSoapEnvelopeEndAndClose(writer); } return(result.ToString()); }
private static async Task <string> BuildAtomFeed( PagedQueryable <PostalInformationSyndicationQueryResult> pagedPostalInfoItems, IOptions <ResponseOptions> responseOptions, IConfiguration configuration) { var sw = new StringWriterWithEncoding(Encoding.UTF8); using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings { Async = true, Indent = true, Encoding = sw.Encoding })) { var formatter = new AtomFormatter(null, xmlWriter.Settings) { UseCDATA = true }; var writer = new AtomFeedWriter(xmlWriter, null, formatter); var syndicationConfiguration = configuration.GetSection("Syndication"); await writer.WriteDefaultMetadata( syndicationConfiguration["Id"], syndicationConfiguration["Title"], Assembly.GetEntryAssembly().GetName().Version.ToString(), new Uri(syndicationConfiguration["Self"]), syndicationConfiguration.GetSection("Related").GetChildren().Select(c => c.Value).ToArray()); var nextUri = BuildVolgendeUri(pagedPostalInfoItems.PaginationInfo, syndicationConfiguration["NextUri"]); if (nextUri != null) { await writer.Write(new SyndicationLink(nextUri, GrArAtomLinkTypes.Next)); } foreach (var postalInfo in pagedPostalInfoItems.Items) { await writer.WritePostalInfo(responseOptions, formatter, syndicationConfiguration["Category"], postalInfo); } xmlWriter.Flush(); } return(sw.ToString()); }
public void ValidObjectCanBeSerializedAndDeserializedTest() { var verzoek = new ApkKeuringsverzoekRequestMessage(); // dont set it wil give an error // verzoek.Xsd = "http://www.w3.org/2001/XMLSchema"; // verzoek.Xsi = "http://www.w3.org/2001/XMLSchema-instance"; verzoek.Keuringsverzoek = new Keuringsverzoek(); verzoek.Keuringsverzoek.Apk = "http://www.rdw.nl/apk"; verzoek.Keuringsverzoek.CorrelatieId = "0038c17b-aa10- 4f93-8569- d184fdfc265b"; verzoek.Keuringsverzoek.Keuringsdatum = "12-1-2016"; verzoek.Keuringsverzoek.Xmlns = "http://www.rdw.nl/apk"; verzoek.Keuringsverzoek.Voertuig = new Voertuig(); verzoek.Keuringsverzoek.Voertuig.Kenteken = "BV-01-EG"; verzoek.Keuringsverzoek.Voertuig.Kilometerstand = "12345"; verzoek.Keuringsverzoek.Voertuig.Naam = "A. eigenaar"; verzoek.Keuringsverzoek.Voertuig.Type = "personenauto"; verzoek.Keuringsverzoek.Keuringsinstantie = new Keuringsinstantie(); verzoek.Keuringsverzoek.Keuringsinstantie.Kvk = "3017 51123"; verzoek.Keuringsverzoek.Keuringsinstantie.Naam = "De Groot"; verzoek.Keuringsverzoek.Keuringsinstantie.Plaats = "De heurne"; verzoek.Keuringsverzoek.Keuringsinstantie.Type = "garage"; var serializer = new XmlSerializer(verzoek.GetType()); using (var stream = new StringWriterWithEncoding(Encoding.UTF8)) using (var xmlwriter = XmlWriter.Create(stream)) { serializer.Serialize(xmlwriter, verzoek); var xml = stream.ToString(); using (var reader = new StringReader(xml)) { var deserializer = new XmlSerializer(typeof(ApkKeuringsverzoekRequestMessage)); var obj = deserializer.Deserialize(reader); Assert.IsInstanceOfType(obj, typeof(ApkKeuringsverzoekRequestMessage)); } } }
public async Task <string> WriteRssAsync() { var feed = GetItemCollection(FeedItemCollection); var settings = new XmlWriterSettings { Async = true }; var sw = new StringWriterWithEncoding(Encoding.UTF8); await using var xmlWriter = XmlWriter.Create(sw, settings); var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle(HeadTitle); await writer.WriteDescription(HeadDescription); await writer.Write(new SyndicationLink(new(TrackBackUrl))); await writer.WritePubDate(DateTimeOffset.UtcNow); await writer.WriteCopyright(Copyright); await writer.WriteGenerator(Generator); foreach (var item in feed) { await writer.Write(item); } await xmlWriter.FlushAsync(); xmlWriter.Close(); await sw.FlushAsync(); sw.GetStringBuilder(); var xml = sw.ToString(); return(xml); }
public void OnSalvarAdicaoCommand() { try { HabilitaEdicao = false; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ClasseVeiculosSeguros)); ObservableCollection <ClasseVeiculosSeguros.VeiculoSeguro> _VeiculosSegurosPro = new ObservableCollection <ClasseVeiculosSeguros.VeiculoSeguro>(); ClasseVeiculosSeguros _ClasseVeiculosSegurosPro = new ClasseVeiculosSeguros(); _VeiculosSegurosPro.Add(SeguroSelecionado); _ClasseVeiculosSegurosPro.VeiculosSeguros = _VeiculosSegurosPro; string xmlString; using (StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.UTF8)) { using (XmlTextWriter xw = new XmlTextWriter(sw)) { xw.Formatting = Formatting.Indented; serializer.Serialize(xw, _ClasseVeiculosSegurosPro); xmlString = sw.ToString(); } } InsereSeguroBD(xmlString); Thread CarregaColecaoSeguros_thr = new Thread(() => CarregaColecaoSeguros(SeguroSelecionado.VeiculoID)); CarregaColecaoSeguros_thr.Start(); //_SegurosTemp.Add(SeguroSelecionado); //Seguros = null; //Seguros = new ObservableCollection<ClasseVeiculosSeguros.VeiculoSeguro>(_SegurosTemp); //SelectedIndex = _selectedIndexTemp; //_SegurosTemp.Clear(); //_ClasseVeiculosSegurosPro = null; //_SegurosTemp.Clear(); //_seguroTemp = null; } catch (Exception ex) { } }
public static string GetXml <T>(T obj, XmlSerializer serializer, XmlSerializerNamespaces ns, Encoding encoding) { using (var textWriter = new StringWriterWithEncoding(encoding)) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; // For cosmetic purposes. settings.IndentChars = " "; // For cosmetic purposes. using (var xmlWriter = XmlWriter.Create(textWriter, settings)) { if (ns != null) { serializer.Serialize(xmlWriter, obj, ns); } else { serializer.Serialize(xmlWriter, obj); } } return(textWriter.ToString()); } }
public string ToString(Encoding enc) { if (this != null) { StringWriterWithEncoding tw = new StringWriterWithEncoding(enc); //System.IO.StringWriter tw = new StringWriter(); XmlTextWriter w = new XmlTextWriter(tw); // Format the Output. So its human readable in notepad // Without that everyting is in one line w.Formatting = Formatting.Indented; w.Indentation = 3; WriteTree(this, w, null); return(tw.ToString()); } else { return(""); } }
public override XmlDocument GetSaml() { using (var sw = new StringWriterWithEncoding(Encoding.UTF8)) { var xws = new XmlWriterSettings { OmitXmlDeclaration = false }; using (XmlWriter xw = XmlWriter.Create(sw, xws)) { WriteLogoutRequest(xw); } var samlString = sw.ToString(); var document = new XmlDocument(); document.LoadXml(samlString); return(document); } }
public void Output_JobIsDisposed_CanBeRead() { // Arrange using IJobManager jobManager = TestHelper.CreateJobManager(true); var start = "2000-01-01Z".ToUtcDateOffset(); var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start); TimeProvider.Override(timeMachine); var job = jobManager.Create("my-job"); // Act var writer = new StringWriterWithEncoding(Encoding.UTF8); job.Output = writer; job.Dispose(); // Assert Assert.That(job.Output, Is.EqualTo(writer)); }
public string Serialize <T>(T ObjectToSerialize, string path) { XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType()); XmlWriterSettings settings = new XmlWriterSettings() { Encoding = new UnicodeEncoding(false, false), // no BOM in a .NET string Indent = false, OmitXmlDeclaration = false }; using (StringWriterWithEncoding textWriter = new StringWriterWithEncoding(Encoding.UTF8)) { xmlSerializer.Serialize(textWriter, ObjectToSerialize); //SaveFileDialog sf = new SaveFileDialog(); //sf.FileName = path; //sf.ShowDialog(); //File.WriteAllText(sf.FileName, textWriter.ToString()); File.WriteAllText(@path, textWriter.ToString()); return(textWriter.ToString()); } }
public static ControlResponse GetResponse(Exception ex) { var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, CloseOutput = false }; StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); using (var writer = XmlWriter.Create(builder, settings)) { writer.WriteStartDocument(true); writer.WriteStartElement("SOAP-ENV", "Envelope", NS_SOAPENV); writer.WriteAttributeString(string.Empty, "encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); writer.WriteStartElement("SOAP-ENV", "Body", NS_SOAPENV); writer.WriteStartElement("SOAP-ENV", "Fault", NS_SOAPENV); writer.WriteElementString("faultcode", "500"); writer.WriteElementString("faultstring", ex.Message); writer.WriteStartElement("detail"); writer.WriteRaw("<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\"><errorCode>401</errorCode><errorDescription>Invalid Action</errorDescription></UPnPError>"); writer.WriteFullEndElement(); writer.WriteFullEndElement(); writer.WriteFullEndElement(); writer.WriteFullEndElement(); writer.WriteEndDocument(); } return(new ControlResponse { Xml = builder.ToString(), IsSuccessful = false }); }
protected string serializeObject(object obj) { XmlSerializer serializer; requestPayload = new oadrPayload(); requestPayload.oadrSignedObject = new oadrSignedObject(); requestPayload.oadrSignedObject.Item = obj; // serialize the event serializer = new XmlSerializer(typeof(oadrPayload)); // StringWriter sw = new StringWriter(); StringWriterWithEncoding sw = new StringWriterWithEncoding(Encoding.UTF8); serializer.Serialize(sw, requestPayload); requestBody = sw.ToString(); return(requestBody); }
protected void WriteToXml () { ReportDesignerWriter rpd = new ReportDesignerWriter(); StringWriterWithEncoding writer = new StringWriterWithEncoding(System.Text.Encoding.UTF8); XmlTextWriter xml =XmlHelper.CreatePropperWriter(writer); XmlHelper.CreatePropperDocument(xml); rpd.Save(this.reportModel.ReportSettings,xml); xml.WriteEndElement(); xml.WriteStartElement("SectionCollection"); foreach (ICSharpCode.Reports.Core.BaseSection s in this.reportModel.SectionCollection) { rpd.Save(s,xml); } xml.WriteEndElement(); xml.WriteEndElement(); xml.WriteEndDocument(); stringWriter = writer; xml.Flush(); stringWriter = writer; }
private static void CreateXMLTimbreFiscal(TimbreFiscalDigital oComprobante, string pathXML) { //SERIALIZAMOS.------------------------------------------------- XmlSerializer oXmlSerializar = new XmlSerializer(typeof(TimbreFiscalDigital)); string sXml = ""; using (var sww = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter writter = XmlWriter.Create(sww)) { oXmlSerializar.Serialize(writter, oComprobante); sXml = sww.ToString(); } } //guardamos el string en un archivo System.IO.File.WriteAllText(pathXML, sXml); }
public string Serialize(TRoot root, Encoding encoding, XmlSerializerNamespaces serializerNamespaces) { var stringBuilder = new StringBuilder(); using (var stringWriter = new StringWriterWithEncoding(stringBuilder, encoding)) { using (XmlWriter xmlWriter = GetXmlWriter(stringWriter, encoding)) { if (serializerNamespaces == null) { Serialize(xmlWriter, root); } else { Serialize(xmlWriter, root, serializerNamespaces); } } } string xml = stringBuilder.ToString(); return(xml); }
public async Task <string> WriteAtomAsync() { var feed = GetItemCollection(FeedItemCollection); var settings = new XmlWriterSettings { Async = true }; var sw = new StringWriterWithEncoding(Encoding.UTF8); await using var xmlWriter = XmlWriter.Create(sw, settings); var writer = new AtomFeedWriter(xmlWriter); await writer.WriteTitle(HeadTitle); await writer.WriteSubtitle(HeadDescription); await writer.WriteRights(Copyright); await writer.WriteUpdated(DateTime.UtcNow); await writer.WriteGenerator(Generator, HostUrl, GeneratorVersion); foreach (var item in feed) { await writer.Write(item); } await xmlWriter.FlushAsync(); xmlWriter.Close(); await sw.FlushAsync(); sw.GetStringBuilder(); var xml = sw.ToString(); return(xml); }
public static string Build(IEnumerable<LabelInfo> labels) { using (var writer = new StringWriterWithEncoding(Encoding.Default)) { foreach(var labelInfo in labels) { writer.WriteLine(string.Format("{0}\t{1}}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}", labelInfo.FirstName , labelInfo.LastName , labelInfo.CorpName, labelInfo.Address, labelInfo.PostalCode , labelInfo.City, labelInfo.State , labelInfo.IsoCountryCode , labelInfo)); } } var content = writer.GetStringBuilder().ToString(); return content; }
public static void XMLExport(SqlXml InputXml, SqlString OutputFile) { try { if (!InputXml.IsNull && !OutputFile.IsNull) { XmlDocument doc = new XmlDocument(); doc.LoadXml(InputXml.Value); StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.GetEncoding("ISO-8859-1")); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace, Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1") }; using (XmlWriter writer = XmlWriter.Create(sw, settings)) { doc.Save(writer); } System.IO.File.WriteAllText(OutputFile.ToString(), sw.ToString(), System.Text.Encoding.GetEncoding("ISO-8859-1")); } else { throw new Exception("Parameters must be set"); } } catch { throw; } }
/// <summary> /// Generates the series output. /// </summary> /// <param name="series">The series.</param> /// <returns> /// Generates a XML output /// </returns> public string GenerateSeriesOutput(Series series) { // http://wiki.xbmc.org/index.php?title=Import_-_Export_Library#TV_Shows using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { this.XmlWriterStart(xmlWriter); xmlWriter.WriteStartElement("tvshow"); // Id XWrite.WriteEnclosedElement(xmlWriter, "id", series.SeriesID); // Title XWrite.WriteEnclosedElement(xmlWriter, "title", series.SeriesName); // Rating XWrite.WriteEnclosedElement(xmlWriter, "rating", series.Rating); // Certification XWrite.WriteEnclosedElement(xmlWriter, "mpaa", series.ContentRating); // Votes //XWrite.WriteEnclosedElement(xmlWriter, "votes", series.Votes); // Plot XWrite.WriteEnclosedElement(xmlWriter, "plot", series.Overview); // Runtime XWrite.WriteEnclosedElement(xmlWriter, "runtime", series.Runtime); // Tagline //XWrite.WriteEnclosedElement(xmlWriter, "tagline", series.Tagline); // Thumb // Fanart // Episodeguide xmlWriter.WriteStartElement("episodeguide"); //XWrite.WriteEnclosedElement(xmlWriter, "url", series.EpisodeGuideUrl); // Cache attribute supported: <url cache="73388.xml">http://www.thetvdb.com/api/1D62F2F90030C444/series/73388/all/en.zip</url> xmlWriter.WriteEndElement(); // Genre foreach (string genre in series.Genre) { XWrite.WriteEnclosedElement(xmlWriter, "genre", genre); } // Director //XWrite.WriteEnclosedElement(xmlWriter, "director", series.Director); // Premiered if (series.FirstAired != null) { XWrite.WriteEnclosedElement( xmlWriter, "premiered", series.FirstAired.Value.ToString("yyyy-MM-dd")); } // Status XWrite.WriteEnclosedElement(xmlWriter, "aired", series.Status); // Aired XWrite.WriteEnclosedElement(xmlWriter, "aired", series.FirstAired); // Studio XWrite.WriteEnclosedElement(xmlWriter, "studio", series.Network); // Trailer //XWrite.WriteEnclosedElement(xmlWriter, "trailer", series.Trailer); // Actor foreach (PersonModel actor in series.Actors) { string role = actor.Role; if (Get.InOutCollection.CleanActorRoles) { role = Regex.Replace(actor.Role, @"\(as.*?\)", string.Empty).Trim(); } xmlWriter.WriteStartElement("actor"); XWrite.WriteEnclosedElement(xmlWriter, "name", actor.Name); XWrite.WriteEnclosedElement(xmlWriter, "role", role); XWrite.WriteEnclosedElement(xmlWriter, "thumb", actor.ImageUrl); xmlWriter.WriteEndElement(); } // Unused in XBMC? // Country //XWrite.WriteEnclosedElement(xmlWriter, "country", series.Country); xmlWriter.WriteEndElement(); } return stringWriter.ToString(); } }
/// <summary> /// Generates the single episode output. /// </summary> /// <param name="episode">The episode.</param> /// <param name="writeDocumentTags">if set to <c>true</c> [write document tags].</param> /// <returns> /// Episode Output /// </returns> public string GenerateSingleEpisodeOutput(Episode episode, bool writeDocumentTags) { using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { if (writeDocumentTags) { this.XmlWriterStart(xmlWriter); } xmlWriter.WriteStartElement("episodedetails"); // Season int? sn = episode.SeasonNumber; if (sn == null || sn < 0) sn = 0; XWrite.WriteEnclosedElement(xmlWriter, "season", sn); // Episode XWrite.WriteEnclosedElement(xmlWriter, "episode", episode.EpisodeNumber); // Title XWrite.WriteEnclosedElement(xmlWriter, "title", episode.EpisodeName); // Rating XWrite.WriteEnclosedElement(xmlWriter, "rating", episode.Rating); // Plot XWrite.WriteEnclosedElement(xmlWriter, "plot", episode.Overview); // Thumb // Playcount //XWrite.WriteEnclosedElement(xmlWriter, "playcount", episode.PlayCount); // Lastplayed //XWrite.WriteEnclosedElement(xmlWriter, "lastplayed", episode.LastPlayed); // Credits //XWrite.WriteEnclosedElement(xmlWriter, "credits", episode.Credits); // Director foreach (PersonModel director in episode.Director) { XWrite.WriteEnclosedElement(xmlWriter, "director", director.Name); } // Aired XWrite.WriteEnclosedElement(xmlWriter, "aired", episode.FirstAired); // Premiered //XWrite.WriteEnclosedElement(xmlWriter, "premiered", episode.Premiered); // Studio //XWrite.WriteEnclosedElement(xmlWriter, "studio", episode.Studio); // Mpaa //XWrite.WriteEnclosedElement(xmlWriter, "mpaa", episode.Mpaa); // Displayepisode: For TV show specials, determines how the episode is sorted in the series //XWrite.WriteEnclosedElement(xmlWriter, "displayepisode", episode.DisplayEpisode); // Actor int count = 1; foreach (PersonModel actor in episode.GuestStars) { count++; xmlWriter.WriteStartElement("actor"); string role = actor.Role; if (Get.InOutCollection.CleanActorRoles) { role = Regex.Replace(actor.Role, @"\(as.*?\)", string.Empty).Trim(); } XWrite.WriteEnclosedElement(xmlWriter, "name", actor.Name); XWrite.WriteEnclosedElement(xmlWriter, "role", role); XWrite.WriteEnclosedElement(xmlWriter, "thumb", actor.ImageUrl); xmlWriter.WriteEndElement(); if (count == 10) { break; } } // Fileinfo XWrite.WriteEnclosedElement(xmlWriter, "fileinfo", "template"); xmlWriter.WriteEndElement(); if (writeDocumentTags) { xmlWriter.WriteEndDocument(); } } return stringWriter.ToString().Replace("<fileinfo>template</fileinfo>", this.GetFileInfo(episode: episode)); } }
/// <summary> /// Generates the series output. /// </summary> /// <param name="series">The series.</param> /// <returns> /// Generates a XML output /// </returns> public string GenerateSeriesOutput(Series series) { using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { this.XmlWriterStart(xmlWriter); xmlWriter.WriteStartElement("tvshow"); // Id XWrite.WriteEnclosedElement(xmlWriter, "id", series.SeriesID); // Title XWrite.WriteEnclosedElement(xmlWriter, "title", series.SeriesName); // Rating XWrite.WriteEnclosedElement(xmlWriter, "rating", series.Rating); // Plot XWrite.WriteEnclosedElement(xmlWriter, "plot", series.Overview); // Certification XWrite.WriteEnclosedElement(xmlWriter, "certification", series.ContentRating); // Genre foreach (string genre in series.Genre) { XWrite.WriteEnclosedElement(xmlWriter, "genre", genre); } // Premiered if (series.FirstAired != null) { XWrite.WriteEnclosedElement( xmlWriter, "premiered", series.FirstAired.Value.ToString("yyyy-MM-dd")); } // Company XWrite.WriteEnclosedElement(xmlWriter, "company", series.Network); // Country XWrite.WriteEnclosedElement(xmlWriter, "country", series.Country); // Actor foreach (PersonModel actor in series.Actors) { string role = actor.Role; if (Get.InOutCollection.CleanActorRoles) { role = Regex.Replace(actor.Role, @"\(as.*?\)", string.Empty).Trim(); } xmlWriter.WriteStartElement("actor"); XWrite.WriteEnclosedElement(xmlWriter, "name", actor.Name); XWrite.WriteEnclosedElement(xmlWriter, "role", role); XWrite.WriteEnclosedElement(xmlWriter, "thumb", actor.ImageUrl); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } return stringWriter.ToString(); } }
/// <summary> /// Generates the movie output. /// </summary> /// <param name="movieModel">The movie model.</param> /// <returns> /// Generates a Movie NFO /// </returns> public string GenerateMovieOutput(MovieModel movieModel) { using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { this.XmlWriterStart(xmlWriter); xmlWriter.WriteStartElement("movie"); // Title XWrite.WriteEnclosedElement(xmlWriter, "title", movieModel.Title); // Original title XWrite.WriteEnclosedElement(xmlWriter, "originaltitle", movieModel.OriginalTitle); // Sort title //XWrite.WriteEnclosedElement(xmlWriter, "sorttitle", movieModel.SortTitle); // Support needed // Sets List<SetReturnModel> sets = MovieSetManager.GetSetReturnList(movieModel); if (sets.Count > 0) { foreach (SetReturnModel set in sets) { // I'm not sure set order is supported by XBMC, however, sorttile after a set seem to. See: http://forum.xbmc.org/showthread.php?t=103441 XWrite.WriteEnclosedElement(xmlWriter, "set", set.SetName); } } // Rating XWrite.WriteEnclosedElement(xmlWriter, "rating", this.ProcessRating(movieModel.Rating).Replace(",", ".")); // Year XWrite.WriteEnclosedElement(xmlWriter, "year", movieModel.Year); // Release Date XWrite.WriteEnclosedElement( xmlWriter, "releasedate", this.ProcessReleaseDate(movieModel.ReleaseDate)); // Top 250 XWrite.WriteEnclosedElement(xmlWriter, "top250", movieModel.Top250); // Votes XWrite.WriteEnclosedElement(xmlWriter, "votes", movieModel.Votes); // Outline XWrite.WriteEnclosedElement(xmlWriter, "outline", movieModel.Outline); // Plot XWrite.WriteEnclosedElement(xmlWriter, "plot", movieModel.Plot); // Tagline XWrite.WriteEnclosedElement(xmlWriter, "tagline", movieModel.Tagline); // Runtime XWrite.WriteEnclosedElement( xmlWriter, "runtime", this.ProcessRuntime(movieModel.Runtime, movieModel.RuntimeInHourMin)); // Thumb /*foreach (string thumb in movieModel.) { XWrite.WriteEnclosedElement(xmlWriter, "thumb", thumb); }*/ // Fanart // Ember Media Manager stores this as /* * <fanart url="http://images.themoviedb.org"> * <thumb preview="http://cf1.imgobject.com/backdrops/065/4bc9af72017a3c181a000065/a-time-to-kill-original_thumb.jpg"> * http://cf1.imgobject.com/backdrops/065/4bc9af72017a3c181a000065/a-time-to-kill-original.jpg * </thumb> * </fanart> */ // Mpaa XWrite.WriteEnclosedElement(xmlWriter, "mpaa", movieModel.Mpaa); // Certification XWrite.WriteEnclosedElement(xmlWriter, "certification", movieModel.Certification); // Playcount //XWrite.WriteEnclosedElement(xmlWriter, "playcount", movieModel.PlayCount); // Support needed // Watched // http://forum.xbmc.org/showthread.php?p=747648 // Maybe this should be replaced by <playcount>1</playcount> XWrite.WriteEnclosedElement(xmlWriter, "watched", movieModel.Watched); // Imdb MovieUniqueId string imdbid = movieModel.ImdbId; if (!string.IsNullOrEmpty(imdbid)) { imdbid = string.Format("tt{0}", imdbid); } XWrite.WriteEnclosedElement(xmlWriter, "id", imdbid); // Trailer try { if (movieModel.TrailerPathOnDisk != null && !movieModel.TrailerPathOnDisk.Equals(String.Empty)) { XWrite.WriteEnclosedElement(xmlWriter, "trailer", movieModel.TrailerPathOnDisk); } else { if (movieModel.CurrentTrailerUrl != null && !movieModel.CurrentTrailerUrl.Equals(String.Empty)) { XWrite.WriteEnclosedElement(xmlWriter, "trailer", movieModel.CurrentTrailerUrl); } else { if (movieModel.AlternativeTrailers.Count > 0) { XWrite.WriteEnclosedElement(xmlWriter, "trailer", movieModel.AlternativeTrailers[0].ToString()); } } } } catch (NullReferenceException e) { } // Genre foreach (string genre in movieModel.Genre) { XWrite.WriteEnclosedElement(xmlWriter, "genre", genre); } // Credits if (movieModel.Writers.Count > 0) { xmlWriter.WriteStartElement("credits"); foreach (PersonModel writer in movieModel.Writers) { XWrite.WriteEnclosedElement(xmlWriter, "writer", writer.Name); } xmlWriter.WriteEndElement(); } // Director foreach (PersonModel director in movieModel.Director) { XWrite.WriteEnclosedElement(xmlWriter, "director", director.Name); } // Actor int count = 1; foreach (PersonModel actor in movieModel.Cast) { count++; xmlWriter.WriteStartElement("actor"); string role = actor.Role; if (Get.InOutCollection.CleanActorRoles) { role = Regex.Replace(actor.Role, @"\(as.*?\)", string.Empty).Trim(); } XWrite.WriteEnclosedElement(xmlWriter, "name", actor.Name); XWrite.WriteEnclosedElement(xmlWriter, "role", role); XWrite.WriteEnclosedElement(xmlWriter, "thumb", actor.ImageUrl); xmlWriter.WriteEndElement(); if (count == 10) { break; } } // Unused in XBMC? // Tmdb MovieUniqueId //XWrite.WriteEnclosedElement(xmlWriter, "id", movieModel.TmdbId, "moviedb", "tmdb"); // Company XWrite.WriteEnclosedElement(xmlWriter, "studio", movieModel.SetStudio); // Country foreach (var country in movieModel.Country) { XWrite.WriteEnclosedElement(xmlWriter, "country", country); } // Unused in XBMC? //XWrite.WriteEnclosedElement(xmlWriter, "videosource", movieModel.VideoSource); // FileInfo XWrite.WriteEnclosedElement(xmlWriter, "fileinfo", "template"); xmlWriter.WriteEndElement(); } return stringWriter.ToString().Replace("<fileinfo>template</fileinfo>", this.GetFileInfo(movie: movieModel)); } }
/// <summary> /// Generates the single episode output. /// </summary> /// <param name="episode">The episode.</param> /// <param name="writeDocumentTags">if set to <c>true</c> [write document tags].</param> /// <returns> /// Episode Output /// </returns> public string GenerateSingleEpisodeOutput(Episode episode, bool writeDocumentTags) { using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { if (writeDocumentTags) { this.XmlWriterStart(xmlWriter); } xmlWriter.WriteStartElement("episodedetails"); // Season int? sn = episode.SeasonNumber; if (sn == null || sn < 0) sn = 0; XWrite.WriteEnclosedElement(xmlWriter, "season", sn); // Episode XWrite.WriteEnclosedElement(xmlWriter, "episode", episode.EpisodeNumber); // Title XWrite.WriteEnclosedElement(xmlWriter, "title", episode.EpisodeName); // Plot XWrite.WriteEnclosedElement(xmlWriter, "plot", episode.Overview); XWrite.WriteEnclosedElement(xmlWriter, "aired", episode.FirstAired); XWrite.WriteEnclosedElement(xmlWriter, "fileinfo", "template"); xmlWriter.WriteEndElement(); if (writeDocumentTags) { xmlWriter.WriteEndDocument(); } } return stringWriter.ToString().Replace("<fileinfo>template</fileinfo>", this.GetFileInfo(episode: episode)); } }
/// <summary> /// Builds the WiX source file (*.wxs) from the specified <see cref="Project"/> instance. /// </summary> /// <param name="project">The <see cref="Project"/> instance.</param> /// <param name="path">The path to the WXS file to be build.</param> /// <param name="type">The type (<see cref="OutputType"/>) of the setup file to be defined in the source file (MSI vs. MSM).</param> /// <returns>Path to the built WXS file.</returns> public static string BuildWxs(Project project, string path, OutputType type) { //very important to keep "ClientAssembly = " in all "public Build*" methods to ensure GetCallingAssembly //returns the build script assembly but not just another method of Compiler. if (ClientAssembly.IsEmpty()) ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().Location; XDocument doc = GenerateWixProj(project); IndjectCustomUI(project.CustomUI, doc); DefaultWixSourceGeneratedHandler(doc); AutoElements.InjectAutoElementsHandler(doc); AutoElements.NormalizeFilePaths(doc, project.SourceBaseDir, EmitRelativePaths); if (type == OutputType.MSM) { //remove all pure MSI elements ConvertMsiToMsm(doc); } project.InvokeWixSourceGenerated(doc); if (WixSourceGenerated != null) WixSourceGenerated(doc); string xml = ""; using (IO.StringWriter sw = new StringWriterWithEncoding(project.Encoding)) { doc.Save(sw, SaveOptions.None); xml = sw.ToString(); } //of course you can use XmlTextWriter.WriteRaw but this is just a temporary quick'n'dirty solution //http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2657663&SiteID=1 xml = xml.Replace("xmlns=\"\"", ""); DefaultWixSourceFormatedHandler(ref xml); project.InvokeWixSourceFormated(ref xml); if (WixSourceFormated != null) WixSourceFormated(ref xml); using (var sw = new IO.StreamWriter(path, false, project.Encoding)) sw.WriteLine(xml); Console.WriteLine("\n----------------------------------------------------------\n"); Console.WriteLine("Wix project file has been built: " + path + "\n"); project.InvokeWixSourceSaved(path); if (WixSourceSaved != null) WixSourceSaved(path); return path; }
/// <summary> /// Generates the movie output. /// </summary> /// <param name="movieModel">The movie model.</param> /// <returns> /// Generates a Movie NFO /// </returns> public string GenerateMovieOutput(MovieModel movieModel) { using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { this.XmlWriterStart(xmlWriter); xmlWriter.WriteStartElement("movie"); // Title XWrite.WriteEnclosedElement(xmlWriter, "title", movieModel.Title); // Year XWrite.WriteEnclosedElement(xmlWriter, "year", movieModel.Year); // Top 250 XWrite.WriteEnclosedElement(xmlWriter, "top250", movieModel.Top250); // Release Date XWrite.WriteEnclosedElement( xmlWriter, "releasedate", this.ProcessReleaseDate(movieModel.ReleaseDate)); // Rating XWrite.WriteEnclosedElement(xmlWriter, "rating", this.ProcessRating(movieModel.Rating).Replace(",", ".")); // Votes XWrite.WriteEnclosedElement(xmlWriter, "votes", movieModel.Votes); // Plot XWrite.WriteEnclosedElement(xmlWriter, "plot", movieModel.Plot); // Tagline XWrite.WriteEnclosedElement(xmlWriter, "tagline", movieModel.Tagline); // Runtime XWrite.WriteEnclosedElement( xmlWriter, "runtime", this.ProcessRuntime(movieModel.Runtime, movieModel.RuntimeInHourMin)); // Mpaa XWrite.WriteEnclosedElement(xmlWriter, "mpaa", movieModel.Mpaa); // Certification XWrite.WriteEnclosedElement(xmlWriter, "certification", movieModel.Certification); // Watched XWrite.WriteEnclosedElement(xmlWriter, "watched", movieModel.Watched); // Imdb MovieUniqueId string imdbid = movieModel.ImdbId; if (!string.IsNullOrEmpty(imdbid)) { imdbid = string.Format("tt{0}", imdbid); } XWrite.WriteEnclosedElement(xmlWriter, "id", imdbid); // Tmdb MovieUniqueId XWrite.WriteEnclosedElement(xmlWriter, "id", movieModel.TmdbId, "moviedb", "tmdb"); // Genre foreach (string genre in movieModel.Genre) { XWrite.WriteEnclosedElement(xmlWriter, "genre", genre); } // Credits if (movieModel.Writers.Count > 0) { xmlWriter.WriteStartElement("credits"); foreach (PersonModel writer in movieModel.Writers) { XWrite.WriteEnclosedElement(xmlWriter, "writer", writer.Name); } xmlWriter.WriteEndElement(); } // Director string writerList = movieModel.WritersAsString.Replace(",", " / "); XWrite.WriteEnclosedElement(xmlWriter, "director", writerList); // Company XWrite.WriteEnclosedElement(xmlWriter, "company", movieModel.SetStudio); // Country foreach (var country in movieModel.Country) { XWrite.WriteEnclosedElement(xmlWriter, "country", country); } // Actor int count = 1; foreach (PersonModel actor in movieModel.Cast) { count++; xmlWriter.WriteStartElement("actor"); string role = actor.Role; if (Get.InOutCollection.CleanActorRoles) { role = Regex.Replace(actor.Role, @"\(as.*?\)", string.Empty).Trim(); } XWrite.WriteEnclosedElement(xmlWriter, "name", actor.Name); XWrite.WriteEnclosedElement(xmlWriter, "role", role); XWrite.WriteEnclosedElement(xmlWriter, "thumb", actor.ImageUrl); xmlWriter.WriteEndElement(); if (count == 10) { break; } } // Sets List<SetReturnModel> sets = MovieSetManager.GetSetReturnList(movieModel); if (sets.Count > 0) { xmlWriter.WriteStartElement("movie"); foreach (SetReturnModel set in sets) { if (set.Order == null) { XWrite.WriteEnclosedElement(xmlWriter, "set", set.SetName); } else { XWrite.WriteEnclosedElement( xmlWriter, "set", set.SetName, "order", set.Order.ToString()); } } xmlWriter.WriteEndElement(); } XWrite.WriteEnclosedElement(xmlWriter, "videosource", movieModel.VideoSource); XWrite.WriteEnclosedElement(xmlWriter, "fileinfo", "template"); xmlWriter.WriteEndElement(); } return stringWriter.ToString().Replace("<fileinfo>template</fileinfo>", this.GetFileInfo(movie: movieModel)); } }
/// <summary> /// Builds the WiX source file (*.wxs) from the specified <see cref="Bundle"/> instance. /// </summary> /// <param name="project">The project.</param> /// <returns></returns> public static string BuildWxs(Bundle project) { lock (typeof(Compiler)) { //very important to keep "ClientAssembly = " in all "public Build*" methods to ensure GetCallingAssembly //returns the build script assembly but not just another method of Compiler. if (ClientAssembly.IsEmpty()) ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().Location; WixEntity.ResetIdGenerator(); string file = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, project.OutFileName) + ".wxs"); if (IO.File.Exists(file)) IO.File.Delete(file); string extraNamespaces = project.WixNamespaces.Distinct() .Select(x => x.StartsWith("xmlns:") ? x : "xmlns:" + x) .ConcatItems(" "); var doc = XDocument.Parse( @"<?xml version=""1.0"" encoding=""utf-8""?> <Wix xmlns=""http://schemas.microsoft.com/wix/2006/wi"" " + extraNamespaces + @"> </Wix>"); doc.Root.Add(project.ToXml()); AutoElements.NormalizeFilePaths(doc, project.SourceBaseDir, EmitRelativePaths); project.InvokeWixSourceGenerated(doc); if (WixSourceGenerated != null) WixSourceGenerated(doc); string xml = ""; using (IO.StringWriter sw = new StringWriterWithEncoding(Encoding.Default)) { doc.Save(sw, SaveOptions.None); xml = sw.ToString(); } //of course you can use XmlTextWriter.WriteRaw but this is just a temporary quick'n'dirty solution //http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2657663&SiteID=1 xml = xml.Replace("xmlns=\"\"", ""); DefaultWixSourceFormatedHandler(ref xml); project.InvokeWixSourceFormated(ref xml); if (WixSourceFormated != null) WixSourceFormated(ref xml); using (var sw = new IO.StreamWriter(file, false, Encoding.Default)) sw.WriteLine(xml); Console.WriteLine("\n----------------------------------------------------------\n"); Console.WriteLine("Wix project file has been built: " + file + "\n"); project.InvokeWixSourceSaved(file); if (WixSourceSaved != null) WixSourceSaved(file); return file; } }
public string GetFileInfo(MovieModel movie = null, Episode episode = null) { FileInfoModel fileInfoModel; if (movie != null) { fileInfoModel = movie.FileInfo; } else if (episode != null) { fileInfoModel = episode.FileInfo; } else { return string.Empty; } string output; using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (var xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { XWrite.WriteEnclosedElement(xmlWriter, "videooutput", Get.MediaInfo.DoReplace(fileInfoModel)); } output = stringWriter.ToString() + Environment.NewLine; } using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (var xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { xmlWriter.WriteStartElement("fileinfo"); xmlWriter.WriteStartElement("video"); // Codec XWrite.WriteEnclosedElement(xmlWriter, "codec", fileInfoModel.Codec); // Aspect XWrite.WriteEnclosedElement(xmlWriter, "aspect", fileInfoModel.AspectRatio); // Width XWrite.WriteEnclosedElement(xmlWriter, "width", fileInfoModel.Width); // Height XWrite.WriteEnclosedElement(xmlWriter, "height", fileInfoModel.Height); xmlWriter.WriteEndElement(); foreach (var audioStream in fileInfoModel.AudioStreams) { xmlWriter.WriteStartElement("audio"); // Codec XWrite.WriteEnclosedElement(xmlWriter, "codec", audioStream.CodecID); // Language XWrite.WriteEnclosedElement(xmlWriter, "codec", audioStream.Language); // Channels XWrite.WriteEnclosedElement(xmlWriter, "channels", audioStream.Channels); xmlWriter.WriteEndElement(); } foreach (var subtitleStream in fileInfoModel.SubtitleStreams) { xmlWriter.WriteStartElement("subtitle"); // Codec XWrite.WriteEnclosedElement(xmlWriter, "codec", subtitleStream.Language); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } return Regex.Replace(output + stringWriter, @"\<\?xml.*?\>", string.Empty) .Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine) .Trim(); } }
private static void UpdateServiceDefinition(IVsTextLines lines, string roleType, string projectName) { if (lines == null) { throw new ArgumentException("lines"); } int lastLine, lastIndex; string text; ErrorHandler.ThrowOnFailure(lines.GetLastLineIndex(out lastLine, out lastIndex)); ErrorHandler.ThrowOnFailure(lines.GetLineText(0, 0, lastLine, lastIndex, out text)); var doc = new XmlDocument(); doc.LoadXml(text); UpdateServiceDefinition(doc, roleType, projectName); var encoding = Encoding.UTF8; var userData = lines as IVsUserData; if (userData != null) { var guid = VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingVSTFF_guid; object data; int cp; if (ErrorHandler.Succeeded(userData.GetData(ref guid, out data)) && (cp = (data as int? ?? (int)(data as uint? ?? 0)) & (int)__VSTFF.VSTFF_CPMASK) != 0) { try { encoding = Encoding.GetEncoding(cp); } catch (NotSupportedException) { } catch (ArgumentException) { } } } var sw = new StringWriterWithEncoding(encoding); doc.Save(XmlWriter.Create( sw, new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineHandling = NewLineHandling.Entitize, Encoding = encoding } )); var sb = sw.GetStringBuilder(); var len = sb.Length; var pStr = Marshal.StringToCoTaskMemUni(sb.ToString()); try { ErrorHandler.ThrowOnFailure(lines.ReplaceLines(0, 0, lastLine, lastIndex, pStr, len, new TextSpan[1])); } finally { Marshal.FreeCoTaskMem(pStr); } }
/// <summary> /// Generates the single episode output. /// </summary> /// <param name="episode">The episode.</param> /// <param name="writeDocumentTags">if set to <c>true</c> [write document tags].</param> /// <returns> /// Episode Output /// </returns> public string GenerateSingleEpisodeOutput(Episode episode, bool writeDocumentTags) { using (var stringWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, this.GetSettings())) { if (writeDocumentTags) { this.XmlWriterStart(xmlWriter); } xmlWriter.WriteStartElement("episodedetails"); // Season XWrite.WriteEnclosedElement(xmlWriter, "season", episode.SeasonNumber); // Episode XWrite.WriteEnclosedElement(xmlWriter, "episode", episode.EpisodeNumber); // Title XWrite.WriteEnclosedElement(xmlWriter, "title", episode.EpisodeName); // Plot XWrite.WriteEnclosedElement(xmlWriter, "plot", episode.Overview); xmlWriter.WriteEndElement(); if (writeDocumentTags) { xmlWriter.WriteEndDocument(); } } return stringWriter.ToString(); } }
/// <summary> /// Builds the WiX source file (*.wxs) from the specified <see cref="Project"/> instance. /// </summary> /// <param name="project">The <see cref="Project"/> instance.</param> /// <param name="path">The path to the WXS file to be build.</param> /// <param name="type">The type (<see cref="OutputType"/>) of the setup file to be defined in the source file (MSI vs. MSM).</param> /// <returns>Path to the built WXS file.</returns> public static string BuildWxs(Project project, string path, OutputType type) { //very important to keep "ClientAssembly = " in all "public Build*" methods to ensure GetCallingAssembly //returns the build script assembly but not just another method of Compiler. if (ClientAssembly.IsEmpty()) ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().Location; XDocument doc = GenerateWixProj(project); IndjectCustomUI(project.CustomUI, doc); DefaultWixSourceGeneratedHandler(doc); AutoElements.InjectAutoElementsHandler(doc); AutoElements.NormalizeFilePaths(doc, project.SourceBaseDir, EmitRelativePaths); if (type == OutputType.MSM) { //remove all pure MSI elements ConvertMsiToMsm(doc); } //issue#63 Inconsistent XML namespace usage in generated Wix source doc.AddDefaultNamespaces(); project.InvokeWixSourceGenerated(doc); if (WixSourceGenerated != null) WixSourceGenerated(doc); doc.AddDefaultNamespaces(); string xml = ""; using (IO.StringWriter sw = new StringWriterWithEncoding(project.Encoding)) { doc.Save(sw, SaveOptions.None); xml = sw.ToString(); } DefaultWixSourceFormatedHandler(ref xml); project.InvokeWixSourceFormated(ref xml); if (WixSourceFormated != null) WixSourceFormated(ref xml); using (var sw = new IO.StreamWriter(path, false, project.Encoding)) sw.WriteLine(xml); Console.WriteLine("\n----------------------------------------------------------\n"); Console.WriteLine("Wix project file has been built: " + path + "\n"); project.InvokeWixSourceSaved(path); if (WixSourceSaved != null) WixSourceSaved(path); return path; }
public ActionResult Feed(string slug, int userID, string type, string extension) { DidacheDb db = new DidacheDb(); Course course = Didache.Courses.GetCourseBySlug(slug); User user = Users.GetUser(userID); if (user == null || course == null) return HttpNotFound(); // BEING XML/RSS StringWriter sw = new StringWriterWithEncoding(Encoding.UTF8); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.Indented; //Response.ContentType = "application/rss+xml"; //Response.ContentEncoding = Encoding.UTF8; writer.WriteStartDocument(); // write RSS 2.0 starter writer.WriteStartElement("rss"); writer.WriteAttributeString("version", "2.0"); writer.WriteAttributeString("xmlns", "itunes", null, "http://www.itunes.com/dtds/podcast-1.0.dtd"); writer.WriteStartElement("channel"); writer.WriteElementString("title", "DTS-" + course.CourseCode + course.Section + "-" + course.Name); writer.WriteElementString("link", "https://online.dts.edu/courses/" + course.Slug); writer.WriteElementString("description", ""); //course.Description); writer.WriteElementString("language", user.Language); writer.WriteElementString("docs", "http://blogs.law.harvard.edu/tech/rss"); writer.WriteElementString("copyright", "This work is copyright 2004-" + DateTime.Now.Year + " by Dallas Theological Seminary and the individual speakers."); //writer.WriteElementString("lastBuildDate", mediaItems[0].OnlineDate.ToString("ddd, d MMM yyyy hh:mm:ss") + " CST"); writer.WriteElementString("webMaster", "[email protected] (Dallas Theological Seminary)"); writer.WriteElementString("category", "Religion"); // get current and next two units for this course DateTime unitStartDate = DateTime.Now.AddDays(21); //List<Unit> units = db.Units.Where(u => u.CourseID == course.CourseID && u.StartDate <= unitStartDate).ToList(); List<Unit> units = db.Units.Where(u => u.CourseID == course.CourseID).ToList(); // get all vidoes List<VideoInfo> videoInfos = GetVideoInfo(course, userID); foreach (Unit unit in units) { foreach (VideoInfo videoInfo in videoInfos.Where(vi => vi.UnitNumber == unit.SortOrder)) { //string videoName = videoInfo.Title; //int videoNumber = videoInfo.SortOrder; //string duration = videoInfo.Duration; // video writer.WriteStartElement("item"); writer.WriteElementString("title", String.Format("{0} unit {1} video {2}", course.CourseCode, unit.SortOrder, videoInfo.SortOrder)); writer.WriteElementString("link", videoInfo.VideoUrl); writer.WriteElementString("description", videoInfo.Title); writer.WriteElementString("author", videoInfo.Speaker); writer.WriteElementString("pubDate", unit.StartDate.AddMinutes(videoInfo.SortOrder).ToString("ddd, d MMM yyyy hh:mm:ss") + " CST"); //"DDD, dd MMM yyyy HH:mm:ss" // VIDEO writer.WriteStartElement("enclosure"); writer.WriteAttributeString("url", videoInfo.VideoUrl); //writer.WriteAttributeString("length", mediaItem.VideoBytesLength.ToString()); writer.WriteAttributeString("type", "video/mp4"); writer.WriteEndElement(); // enclosure writer.WriteStartElement("guid"); writer.WriteAttributeString("isPermaLink", "false"); writer.WriteString(String.Format("video-c{0}u{1}v{2}", course.CourseCode, unit.SortOrder, videoInfo.SortOrder)); writer.WriteEndElement(); // guid writer.WriteStartElement("itunes", "author", null); writer.WriteString(videoInfo.Speaker); writer.WriteEndElement(); writer.WriteStartElement("itunes", "subtitle", null); writer.WriteString(videoInfo.Title); writer.WriteEndElement(); writer.WriteStartElement("itunes", "summary", null); writer.WriteString(videoInfo.Title); writer.WriteEndElement(); writer.WriteStartElement("itunes", "duration", null); writer.WriteString(videoInfo.Duration); writer.WriteEndElement(); writer.WriteEndElement(); // item /* // PDF transcript writer.WriteStartElement("item"); writer.WriteElementString("title", String.Format("{0} unit {1} video {2} transcript", course.CourseCode, unit.SortOrder, videoInfo.SortOrder)); writer.WriteElementString("link", "https://online.dts.edu/courses/" + course.Slug + "/schedule/" + unit.UnitID.ToString()); writer.WriteElementString("description", videoInfo.Title); writer.WriteElementString("author", videoInfo.Speaker); writer.WriteElementString("pubDate", unit.StartDate.AddMinutes(videoInfo.SortOrder).ToString("ddd, d MMM yyyy hh:mm:ss") + " CST"); //"DDD, dd MMM yyyy HH:mm:ss" // PDF transcript writer.WriteStartElement("enclosure"); writer.WriteAttributeString("url", videoInfo.TranscriptUrl); writer.WriteAttributeString("type", "application/pdf"); writer.WriteEndElement(); // enclosure writer.WriteStartElement("guid"); writer.WriteAttributeString("isPermaLink", "false"); writer.WriteString(String.Format("transcript-c{0}u{1}v{2}", course.CourseCode, unit.SortOrder, videoInfo.SortOrder)); writer.WriteEndElement(); // guid writer.WriteStartElement("itunes", "author", null); writer.WriteString(videoInfo.Speaker); writer.WriteEndElement(); writer.WriteStartElement("itunes", "subtitle", null); writer.WriteString(videoInfo.Title); writer.WriteEndElement(); writer.WriteStartElement("itunes", "summary", null); writer.WriteString(videoInfo.Title); writer.WriteEndElement(); writer.WriteStartElement("itunes", "duration", null); writer.WriteString(videoInfo.Duration); writer.WriteEndElement(); writer.WriteEndElement(); // item // PDF Slides writer.WriteStartElement("item"); writer.WriteElementString("title", String.Format("{0} unit {1} video {2} slides", course.CourseCode, unit.SortOrder, videoInfo.SortOrder)); writer.WriteElementString("link", "https://online.dts.edu/courses/" + course.Slug + "/schedule/" + unit.UnitID.ToString()); writer.WriteElementString("description", videoInfo.Title); writer.WriteElementString("author", videoInfo.Speaker); writer.WriteElementString("pubDate", unit.StartDate.AddMinutes(videoInfo.SortOrder).ToString("ddd, d MMM yyyy hh:mm:ss") + " CST"); //"DDD, dd MMM yyyy HH:mm:ss" // PDF slides writer.WriteStartElement("enclosure"); writer.WriteAttributeString("url", videoInfo.SlidesUrl); writer.WriteAttributeString("type", "application/pdf"); writer.WriteEndElement(); // enclosure writer.WriteStartElement("guid"); writer.WriteAttributeString("isPermaLink", "false"); writer.WriteString(String.Format("slides-c{0}u{1}v{2}", course.CourseCode, unit.SortOrder, videoInfo.SortOrder)); writer.WriteEndElement(); // guid writer.WriteStartElement("itunes", "author", null); writer.WriteString(videoInfo.Speaker); writer.WriteEndElement(); writer.WriteStartElement("itunes", "subtitle", null); writer.WriteString(videoInfo.Title); writer.WriteEndElement(); writer.WriteStartElement("itunes", "summary", null); writer.WriteString(videoInfo.Title); writer.WriteEndElement(); writer.WriteStartElement("itunes", "duration", null); writer.WriteString(videoInfo.Duration); writer.WriteEndElement(); writer.WriteEndElement(); // item */ } } writer.WriteEndElement(); // channel writer.WriteEndElement(); // rss writer.WriteEndDocument(); writer.Flush(); writer.Close(); return Content(sw.ToString(), "text/xml", Encoding.UTF8); }
public static string Serialize(object Obj) { StringBuilder sb = new StringBuilder(); StringWriterWithEncoding HappyStringWriter = new StringWriterWithEncoding(sb, Encoding.UTF8); XmlSerializer x = new XmlSerializer(Obj.GetType()); x.Serialize(HappyStringWriter, Obj); return HappyStringWriter.ToString(); }
public static string GenerateMovieMeterXml(DownloadItem downloadItem, string idType, string value) { var apiProxy = (IMMApi)XmlRpcProxyGen.Create(typeof(IMMApi)); const string imdb = "imdb"; const string search = "search"; var filmDetail = new FilmDetail(); if (idType == imdb) { value = apiProxy.RetrieveByImdb(getSessionKey(), value); } else if (idType == search) { var filmlist = apiProxy.Search(getSessionKey(), value); if (filmlist.Length > 0) { value = filmlist[0].filmId; } else { return string.Empty; } } filmDetail = apiProxy.RetrieveDetails(getSessionKey(), value.ToInt()); var movieMeter = new MovieMeter(); using (var stringWriter = new StringWriterWithEncoding(movieMeter.HtmlEncoding)) { using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter)) { xmlWriter.WriteStartElement("moviemeter"); XWrite.WriteEnclosedElement(xmlWriter, "id", filmDetail.filmId); XWrite.WriteEnclosedElement(xmlWriter, "imdbid", filmDetail.imdb); XWrite.WriteEnclosedElement(xmlWriter, "title", filmDetail.title); XWrite.WriteEnclosedElement(xmlWriter, "year", filmDetail.year); foreach (var actor in filmDetail.actors) { XWrite.WriteEnclosedElement(xmlWriter, "actor", actor.name); } foreach (var genre in filmDetail.genres) { XWrite.WriteEnclosedElement(xmlWriter, "genre", genre); } XWrite.WriteEnclosedElement(xmlWriter, "plot", filmDetail.plot); foreach (var actor in filmDetail.directors) { XWrite.WriteEnclosedElement(xmlWriter, "director", actor.name); } XWrite.WriteEnclosedElement(xmlWriter, "releasedate", filmDetail.dates_cinema[0].date); foreach (var country in filmDetail.countries) { XWrite.WriteEnclosedElement(xmlWriter, "country", country.name, "code", country.iso_3166_1); } XWrite.WriteEnclosedElement(xmlWriter, "countries", filmDetail.countries_text); XWrite.WriteEnclosedElement(xmlWriter, "rating", filmDetail.average); xmlWriter.WriteEndElement(); } return stringWriter.ToString(); } }
public override void ProcessHttpRequest(HttpListenerContext context) { // запрос возвращает разметку или JSON? if (context.Request.QueryString.AllKeys.Contains("json") && context.Request.HttpMethod == "GET") { Logger.Info("HTTP GET (JSON) request"); ProcessJsonRequest(context); return; } var messageToPopup = string.Empty; var accountAction = string.Empty; // Текущее действие пользователя, при работе с таблицей счетов if (context.Request.HttpMethod == "POST") { if (context.Request.QueryString.AllKeys.Contains("json")) { Logger.Info("HTTP POST (JSON) request"); ProcessJSONPostRequest(context); return; } Logger.Info("HTTP POST request"); if (context.Request.QueryString.AllKeys.Contains("actionAccount")) if (AccountAjaxJsonAction(context)) return; if (context.Request.QueryString.AllKeys.Contains("editAccountsTable")) messageToPopup = AccountSubmitAction(context, out accountAction); else if (context.Request.QueryString.AllKeys.Contains("updatePortfolio")) messageToPopup = UpdatePortfolio(context, out accountAction); else messageToPopup = ProcessFileUpload(context); } Logger.Info("HTTP GET (regular) request"); #region Сохранить настройки фермы if (context.Request.QueryString.AllKeys.Contains("saveas")) { // выдать результат - настройки RobotFarm в виде XML var doc = new XmlDocument(); if (RobotFarm.Instance.SaveSettings(doc)) { var sbXml = new StringBuilder(); using (var tw = new StringWriterWithEncoding(sbXml, Encoding.UTF8)) using (var xw = XmlWriter.Create(tw)) { doc.Save(xw); } // выдать текст (XML) var resp = Encoding.UTF8.GetBytes(sbXml.ToString()); context.Response.ContentType = "text/xml"; context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentLength64 = resp.Length; context.Response.OutputStream.Write(resp, 0, resp.Length); return; } else messageToPopup = "Ошибка сохранения"; } if (context.Request.QueryString.AllKeys.Contains("actionAccount")) { if (AccountAjaxAction(context)) return; } if (context.Request.QueryString.AllKeys.Contains("actionPortfolio")) { if (PortfolioAjaxAction(context)) return; } if (context.Request.QueryString.AllKeys.Contains("requestTradeSignalCat")) { if (GetTradeSignalCategory(context)) return; } if (context.Request.QueryString.AllKeys.Contains(RequestCloseDealsByAccount)) { if (CloseDealsByAccount(context)) return; } if (context.Request.QueryString.AllKeys.Contains("switchAccountEnabled")) { var accId = context.Request.QueryString["switchAccountEnabled"].ToIntSafe() ?? 0; if (accId == 0) return; // включить / отключить счет var acc = RobotFarm.Instance.Accounts.FirstOrDefault(a => a.AccountId == accId); if (acc == null) return; acc.TradeEnabled = !acc.TradeEnabled; // сообщить - все ОК var resp = string.Format("{{\"enabled\":{0}, \"countEnabled\":\"{1}\"}}", acc.TradeEnabled.ToString().ToLower(), GetTradableAccountsCount()); WriteTextResponse(context, resp); return; } if (context.Request.QueryString.AllKeys.Contains("removeRobot")) { // ферма остановлена? if (RobotFarm.Instance.State != FarmState.Stopped) return; var robotIndex = context.Request.QueryString["removeRobot"].ToIntSafe() ?? -1; if (robotIndex < 0) return; var accId = context.Request.QueryString["forAccount"].ToIntSafe() ?? 0; if (accId == 0) return; var acc = RobotFarm.Instance.GetAccountById(accId); if (acc == null) return; if (robotIndex < acc.Robots.Count) acc.Robots.RemoveAt(robotIndex); const string resp = "{\"status\": \"OK\"}"; WriteTextResponse(context, resp); return; } // запрос на сохранение настроек if (context.Request.QueryString.AllKeys.Contains("saveSettings")) { RobotFarm.Instance.SaveSettings(); // ответить - все гуд, сообщить состояние фермы WriteTextResponse(context, "{\"saved\":\"true\"}"); return; } // запрос на запуск - останов фермы... if (context.Request.QueryString.AllKeys.Contains("startStopFarm")) { RobotFarm.Instance.StartOrStopFarm(); // ответить - все гуд, сообщить состояние фермы WriteTextResponse(context, string.Format("{{\"state\":\"{0}\"}}", RobotFarm.Instance.State)); return; } #endregion // если обычный запрос... var sb = new StringBuilder(); var sbBackImg = new StringBuilder(); RenderImgBytesSrc(sbBackImg, ImgRsxBackground); RenderHttpHead(sb, "",//"body { background-image:url(" + sbBackImg + "); background-repeat: repeat; }", GetScripts(), true); // добавить шапку sb.AppendLine("<body style=\"background-color:#303030;margin:0px;padding-top:10px\">"); RenderPopupDiv(sb, 200, 50, "messageDiv"); sb.AppendLine(" <div style=\"background-color:White;width:800px;margin: auto;text-align: left;padding:10px\">"); // рендерить меню RenderFarmPageMenu(sb, context); // рендерить страницу if (context.Request.QueryString.AllKeys.Contains("log")) RenderServerLog(sb); else if (context.Request.QueryString.AllKeys.Contains("openedPositionsByAccount")) RenderAccountPositions(sb, context.Request.QueryString["openedPositionsByAccount"].ToIntSafe() ?? 0); else if (context.Request.QueryString.AllKeys.Contains("subscriptionsByAccount")) RenderAccountSubscriptions(sb, context.Request.QueryString["subscriptionsByAccount"].ToIntSafe() ?? 0); else if (context.Request.QueryString.AllKeys.Contains("portfolioTradeSettings")) RenderPortfolioSettings(sb); else if (context.Request.QueryString.AllKeys.Contains("trades")) RenderTrades(sb, context.Request.QueryString["trades"].ToIntSafe() ?? 0); else if (context.Request.QueryString.AllKeys.Contains("editAccountsTable")) { switch (accountAction) { case "openNewAccountForm": InsertAddAccountTableControl(sb); break; default: RenderAccountEditTable(sb); InsertAddAccountButtonControl(sb); break; } } else RenderFarmPage(sb, context); // закрыть тег sb.AppendLine(" </div>"); // всплывающее сообщение? if (!string.IsNullOrEmpty(messageToPopup)) sb.AppendLine("<script>showMessage('messageDiv', '" + messageToPopup + "', 1500);</script>"); sb.AppendLine("</body>\r\n</html>"); // записать ответ var r = Encoding.UTF8.GetBytes(sb.ToString()); context.Response.ContentLength64 = r.Length; context.Response.OutputStream.Write(r, 0, r.Length); }