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); }
public override XmlDocument GetSaml() { using (var sw = new StringWriterWithEncoding(Encoding.UTF8)) { var xws = new XmlWriterSettings { OmitXmlDeclaration = false }; using (XmlWriter xw = XmlWriter.Create(sw, xws)) { WriteLogoutResponse(xw); } var samlString = sw.ToString(); var document = new XmlDocument(); document.LoadXml(samlString); return(document); } }
public void OnSalvarAdicaoCommand() { try { HabilitaEdicao = false; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ClasseEmpresasSignatarios)); ObservableCollection <ClasseEmpresasSignatarios.EmpresaSignatario> _EmpresasSignatariosPro = new ObservableCollection <ClasseEmpresasSignatarios.EmpresaSignatario>(); ClasseEmpresasSignatarios _ClasseEmpresasSegnatariosPro = new ClasseEmpresasSignatarios(); _EmpresasSignatariosPro.Add(SignatarioSelecionado); _ClasseEmpresasSegnatariosPro.EmpresasSignatarios = _EmpresasSignatariosPro; string xmlString; using (StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.UTF8)) { using (XmlTextWriter xw = new XmlTextWriter(sw)) { xw.Formatting = Formatting.Indented; serializer.Serialize(xw, _ClasseEmpresasSegnatariosPro); xmlString = sw.ToString(); } } InsereEmpresasSignatariosBD(xmlString); Thread CarregaColecaoEmpresasSignatarios_thr = new Thread(() => CarregaColecaoEmpresasSignatarios(SignatarioSelecionado.EmpresaId)); CarregaColecaoEmpresasSignatarios_thr.Start(); //_SignatarioTemp.Add(SignatarioSelecionado); //Signatarios = null; //Signatarios = new ObservableCollection<ClasseEmpresasSignatarios.EmpresaSignatario>(_SignatarioTemp); //SelectedIndex = _selectedIndexTemp; //_SignatarioTemp.Clear(); //_ClasseEmpresasSegnatariosPro = null; //_EmpresasSignatariosPro.Clear(); } catch (Exception ex) { } }
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); }
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 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 void OnSalvarEdicaoCommand() { try { HabilitaEdicao = false; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ClasseColaboradoresCursos)); ObservableCollection <ClasseColaboradoresCursos.ColaboradorCurso> _ColaboradoresCursosTemp = new ObservableCollection <ClasseColaboradoresCursos.ColaboradorCurso>(); ClasseColaboradoresCursos _ClasseColaboradoresCursosTemp = new ClasseColaboradoresCursos(); _ColaboradoresCursosTemp.Add(ColaboradorCursoSelecionado); _ClasseColaboradoresCursosTemp.ColaboradoresCursos = _ColaboradoresCursosTemp; string xmlString; using (StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.UTF8)) { using (XmlTextWriter xw = new XmlTextWriter(sw)) { xw.Formatting = Formatting.Indented; serializer.Serialize(xw, _ClasseColaboradoresCursosTemp); xmlString = sw.ToString(); } } InsereColaboradorCursoBD(xmlString); Thread CarregaColecaoColaboradorerCursos_thr = new Thread(() => CarregaColecaoColaboradorerCursos(ColaboradorCursoSelecionado.ColaboradorID)); CarregaColecaoColaboradorerCursos_thr.Start(); _ColaboradoresCursosTemp = null; //_ColaboradoresCursosTemp.Clear(); //_ColaboradorCursoTemp = null; } catch (Exception ex) { //Global.Log("Erro void CarregaColecaoEmpresas ex: " + ex.Message); } }
/// <summary> /// Builds sitemap structure /// </summary> /// <param name="sitemapSiteConfiguration">Sitemap site configuration</param> /// <param name="elements"></param> /// <returns>Sitemap content as string</returns> public virtual String BuildSitemap(SitemapSiteConfiguration sitemapSiteConfiguration, IEnumerable <UrlElement> elements) { var result = String.Empty; 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 { foreach (var urlElement in elements) { WriteUrlElement(urlElement, 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 Serialize(object obj, string rootElement) { XmlSerializer srReq; if (string.IsNullOrEmpty(rootElement)) { srReq = new XmlSerializer(obj.GetType()); } else { var root = new XmlRootAttribute(rootElement); srReq = new XmlSerializer(obj.GetType(), root); } var wr = new StringWriterWithEncoding(Encoding.UTF8); srReq.Serialize(wr, obj); string retorno = wr.ToString(); wr.Close(); return(retorno); }
private static string GetString(this XmlSchemaSet xmlSchemaSet) { var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false, false), Indent = true, OmitXmlDeclaration = false }; string output; using (var textWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) { foreach (XmlSchema s in xmlSchemaSet.Schemas()) { s.Write(xmlWriter); } } output = textWriter.ToString(); } return(output); }
private string CreateXmlString() { XmlWriterSettings lWriterSettings = new XmlWriterSettings(); lWriterSettings.Indent = true; lWriterSettings.IndentChars = " "; lWriterSettings.NewLineChars = "\r\n"; lWriterSettings.CheckCharacters = false; lWriterSettings.NewLineHandling = NewLineHandling.Replace; lWriterSettings.Encoding = Encoding.UTF8; var lDocumentBuilder = new StringWriterWithEncoding(Encoding.UTF8); using (XmlWriter lDocumentWriter = XmlWriter.Create(lDocumentBuilder, lWriterSettings)) { _currentDocument.Save(lDocumentWriter); } return(lDocumentBuilder .ToString() .Replace("
", " ") .Replace("&#xA;", " ")); }
public static string Serialize <T>(T value, XmlSerializerNamespaces namespaces, string defaultNamespace) { if (value == null) { return(null); } XmlSerializer serializer = new XmlSerializer(typeof(T), defaultNamespace); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.Indent = false; settings.OmitXmlDeclaration = false; using (StringWriter textWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) { serializer.Serialize(xmlWriter, value, namespaces); } return(textWriter.ToString()); } }
/// <summary> /// </summary> /// <param name="enc"> /// </param> /// <returns> /// </returns> public string ToString(Encoding enc) { if (this != null) { var tw = new StringWriterWithEncoding(enc); // System.IO.StringWriter tw = new StringWriter(); var 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(string.Empty); } }
/// <summary> /// 将对象序列化为xml /// </summary> /// <param name="o"></param> /// <param name="namespaces"></param> /// <param name="xmlRootName"></param> /// <param name="indent"></param> /// <param name="encoding"></param> /// <param name="hasHeader"></param> /// <returns></returns> public static string SerializeObject <T>(T o, XmlSerializerNamespaces namespaces, string xmlRootName = null, bool indent = false, Encoding encoding = null, bool hasHeader = false) { var settings = new XmlWriterSettings { OmitXmlDeclaration = !hasHeader, Indent = indent, IndentChars = " ", Encoding = encoding }; var sb = new StringWriterWithEncoding(encoding); using (var writer = XmlWriter.Create(sb, settings)) { var xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName)); xmlSerializer.Serialize(writer, o, namespaces); } return(sb.ToString()); }
private ControlResponse CreateControlResponse(ControlRequestInfo requestInfo) { 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", NsSoapEnv); writer.WriteAttributeString(string.Empty, "encodingStyle", NsSoapEnv, "http://schemas.xmlsoap.org/soap/encoding/"); writer.WriteStartElement("SOAP-ENV", "Body", NsSoapEnv); writer.WriteStartElement("u", requestInfo.LocalName + "Response", requestInfo.NamespaceURI); WriteResult(requestInfo.LocalName, requestInfo.Headers, writer); writer.WriteFullEndElement(); writer.WriteFullEndElement(); writer.WriteFullEndElement(); writer.WriteEndDocument(); } var xml = builder.ToString().Replace("xmlns:m=", "xmlns:u=", StringComparison.Ordinal); var controlResponse = new ControlResponse(xml, true); controlResponse.Headers.Add("EXT", string.Empty); return(controlResponse); }
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; } }
public static string CreateXml(object obj) { try { using (StringWriter sw = new StringWriterWithEncoding(Encoding.UTF8)) { XmlDocument doc = new XmlDocument(); doc.CreateXmlDeclaration("1.0", sw.Encoding.ToString(), null); XmlNode root = doc.CreateElement("xml"); doc.AppendChild(root); var props = obj.GetType().GetProperties(); foreach (var p in props) { _CraeteChildNode(doc, root, p, obj); } doc.Save(sw); return(sw.ToString()); } } catch (Exception ex) { throw; } }
public static string Serialize <T>(T value) where T : class { if (value == null) { return(null); } XmlSerializer serializer = new XmlSerializer(value.GetType()); // typeof(T)); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = new UnicodeEncoding(false, false); // no BOM in a .NET string settings.Indent = true; ///TODO: Setar para FALSE? settings.OmitXmlDeclaration = false; using (StringWriterWithEncoding textWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) { serializer.Serialize(xmlWriter, value); } return(textWriter.ToString()); } }
private static string Serialize <T>(T value) { if (value == null) { return(string.Empty); } try { var settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.Indent = true; var xmlserializer = new XmlSerializer(typeof(T)); var stringWriter = new StringWriterWithEncoding(new StringBuilder(), Encoding.UTF8); using (var writer = XmlWriter.Create(stringWriter, settings)) { xmlserializer.Serialize(writer, value, new XmlSerializerNamespaces()); return(stringWriter.ToString()); } } catch (Exception ex) { throw new Exception("An error occurred", ex); } }
public void OnSalvarEdicaoCommand() { try { HabilitaEdicao = false; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ClassePendencias)); ObservableCollection <ClassePendencias.Pendencia> _PendenciasTemp = new ObservableCollection <ClassePendencias.Pendencia>(); ClassePendencias _ClassePendenciasTemp = new ClassePendencias(); _PendenciasTemp.Add(PendenciaSelecionada); _ClassePendenciasTemp.Pendencias = _PendenciasTemp; string xmlString; using (StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.UTF8)) { using (XmlTextWriter xw = new XmlTextWriter(sw)) { xw.Formatting = Formatting.Indented; serializer.Serialize(xw, _ClassePendenciasTemp); xmlString = sw.ToString(); } } InserePendenciaBD(xmlString); _PendenciasTemp = null; _PendenciasTemp.Clear(); _PendenciaTemp = null; } catch (Exception ex) { //Global.Log("Erro void CarregaColecaoEmpresas ex: " + ex.Message); } }
public async Task <string> WriteRssAsync() { var feed = GetItemCollection(FeedItemCollection); var sw = new StringWriterWithEncoding(Encoding.UTF8); await using (var xmlWriter = XmlWriter.Create(sw, new() { Async = true })) { 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(); } var xml = sw.ToString(); return(xml); }
/// <summary> /// Generates an XML text equivalent of the specified object. /// </summary> public static string Serialize(object value, bool omitXmlDeclaration = false) { if (value == null) { return(null); } var serializer = new XmlSerializer(value.GetType()); var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, OmitXmlDeclaration = omitXmlDeclaration }; using (var textWriter = new StringWriterWithEncoding(Encoding.UTF8)) { using (var xmlWriter = XmlWriter.Create(textWriter, settings)) serializer.Serialize(xmlWriter, value); return(textWriter.ToString()); } }
public static string Object2Xml <T>(T value, string fileName) { if (value == null) { return(string.Empty); } try { var xmlserializer = new XmlSerializer(typeof(T)); var stringWriter = new StringWriterWithEncoding(Encoding.UTF8); var xmlWriterSetting = new XmlWriterSettings(); xmlWriterSetting.Encoding = Encoding.UTF8; using (var writer = XmlWriter.Create(stringWriter, xmlWriterSetting)) { xmlserializer.Serialize(writer, value); File.WriteAllText(@"C:\Users\Tuan Tran\Desktop\VietnamBusInfo\Data\" + fileName + ".xml", stringWriter.ToString()); return(stringWriter.ToString()); } } catch (Exception ex) { throw new Exception("An error occurred", ex); } }
public async Task WriteImage() { Uri uri = new Uri("http://testuriforlink.com"); var sw = new StringWriterWithEncoding(Encoding.UTF8); using (var xmlWriter = XmlWriter.Create(sw)) { var writer = new RssFeedWriter(xmlWriter); await writer.Write(new SyndicationImage(uri) { Title = "Testing image title", Description = "testing image description", Link = new SyndicationLink(uri) }); await writer.Flush(); } string res = sw.ToString(); Assert.True(res == $"<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><image><url>{uri}</url><title>Testing image title</title><link>{uri}</link><description>testing image description</description></image></channel></rss>"); }
public async Task WriteLink_allElements() { var sw = new StringWriterWithEncoding(Encoding.UTF8); var link = new SyndicationLink(new Uri("http://testuriforlink.com")) { Title = "Test title", Length = 123, MediaType = "mp3/video" }; using (var xmlWriter = XmlWriter.Create(sw)) { var writer = new RssFeedWriter(xmlWriter); await writer.Write(link); await writer.Flush(); } string res = sw.ToString(); Assert.True(res == $"<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><link url=\"{link.Uri}\" type=\"{link.MediaType}\" length=\"{link.Length}\">{link.Title}</link></channel></rss>"); }
/// <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> /// 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 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)); } }
public async Task Routine_SetOnTheFly_CompletesWithOldRoutineAndThenStartsWithNewRoutine() { // 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"); var output = new StringWriterWithEncoding(Encoding.UTF8); job.Output = output; job.Schedule = new SimpleSchedule(SimpleScheduleKind.Second, 1, start); async Task Routine1(object parameter, IProgressTracker tracker, TextWriter writer, CancellationToken token) { await writer.WriteAsync("First Routine!"); await Task.Delay(1500, token); } async Task Routine2(object parameter, IProgressTracker tracker, TextWriter writer, CancellationToken token) { await writer.WriteAsync("Second Routine!"); await Task.Delay(1500, token); } job.IsEnabled = true; job.Routine = Routine1; // Act await timeMachine.WaitUntilSecondsElapse(start, 1.4); job.Routine = Routine2; await timeMachine.WaitUntilSecondsElapse(start, 2.8); var output1 = output.ToString(); await timeMachine.WaitUntilSecondsElapse(start, 4.8); var output2 = output.ToString(); jobManager.Dispose(); var info = job.GetInfo(null); // Assert try { Assert.That(info.NextDueTime, Is.EqualTo(start.AddSeconds(5))); Assert.That(info.CurrentRun, Is.Null); Assert.That(info.RunCount, Is.EqualTo(2)); Assert.That(info.Runs, Has.Count.EqualTo(2)); var run0 = info.Runs[0]; Assert.That(run0.DueTime, Is.EqualTo(start.AddSeconds(1))); Assert.That(run0.Output, Is.EqualTo("First Routine!")); Assert.That(output1, Is.EqualTo("First Routine!")); var run1 = info.Runs[1]; Assert.That(run1.DueTime, Is.EqualTo(start.AddSeconds(3))); Assert.That(run1.Output, Is.EqualTo("Second Routine!")); Assert.That(output2, Is.EqualTo("First Routine!Second Routine!")); } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("*** Test Failed ***"); sb.AppendLine(ex.ToString()); sb.AppendLine("*** Log: ***"); var log = _logWriter.ToString(); sb.AppendLine(log); Assert.Fail(sb.ToString()); } }
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(); } }
/// <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> /// 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)); } }
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(); } }
/// <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 string createdOadrCreatedEvent(string venID, string requestID, List <oadrDistributeEventOadrEvent> evts, OptTypeType optType, int responseCode = 200, string responseDescription = "OK") { this.optType = optType; updatedEvents = evts; createdEvent = new oadrCreatedEvent(); createdEvent.eiCreatedEvent = new eiCreatedEvent(); createdEvent.eiCreatedEvent.eiResponse = new eiResponse(); if (evts.Count != 0) { createdEvent.eiCreatedEvent.eiResponse.requestID = ""; } else { createdEvent.eiCreatedEvent.eiResponse.requestID = requestID; } createdEvent.eiCreatedEvent.eiResponse.responseCode = responseCode.ToString(); createdEvent.eiCreatedEvent.eiResponse.responseDescription = responseDescription; createdEvent.eiCreatedEvent.venID = venID; createdEvent.eiCreatedEvent.eventResponses = new eventResponsesEventResponse[evts.Count]; int index = 0; foreach (oadrDistributeEventOadrEvent evt in evts) { eventResponsesEventResponse eventResponse = new eventResponsesEventResponse(); eventResponse.optType = optType; eventResponse.qualifiedEventID = new QualifiedEventIDType(); eventResponse.qualifiedEventID.eventID = evt.eiEvent.eventDescriptor.eventID; eventResponse.qualifiedEventID.modificationNumber = evt.eiEvent.eventDescriptor.modificationNumber; // eventResponse.requestID = RandomHex.generateRandomHex(10); eventResponse.requestID = requestID; eventResponse.responseCode = responseCode.ToString(); eventResponse.responseDescription = responseDescription; createdEvent.eiCreatedEvent.eventResponses[index] = eventResponse; index++; } XmlSerializer serializer; // serialize the event serializer = new XmlSerializer(typeof(oadrCreatedEvent)); // StringWriter sw = new StringWriter(); StringWriterWithEncoding sw = new StringWriterWithEncoding(Encoding.UTF8); serializer.Serialize(sw, createdEvent); requestBody = sw.ToString(); return(requestBody); }
/// <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)); } }
public async Task Routine_SetAfterPreviousRunCompleted_SetsValueAndRunsWithIt() { // Arrange using IJobManager jobManager = TestHelper.CreateJobManager(true); var job = jobManager.Create("my-job"); var start = "2000-01-01Z".ToUtcDateOffset(); var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start); TimeProvider.Override(timeMachine); var output = new StringWriterWithEncoding(Encoding.UTF8); job.Output = output; JobDelegate routine1 = async(parameter, tracker, writer, token) => { await writer.WriteAsync("First Routine!"); await Task.Delay(1500, token); }; JobDelegate routine2 = async(parameter, tracker, writer, token) => { await writer.WriteAsync("Second Routine!"); await Task.Delay(1500, token); }; job.Schedule = new ConcreteSchedule( start.AddSeconds(1), start.AddSeconds(4)); job.IsEnabled = true; // Act job.Routine = routine1; var updatedRoutine1 = job.Routine; await timeMachine.WaitUntilSecondsElapse(start, 2.9); // job with routine1 will complete var output1 = output.ToString(); await timeMachine.WaitUntilSecondsElapse(start, 3.0); job.Routine = routine2; var updatedRoutine2 = job.Routine; await timeMachine.WaitUntilSecondsElapse(start, 6.0); var output2 = output.ToString(); // Assert try { Assert.That(updatedRoutine1, Is.SameAs(routine1)); Assert.That(output1, Is.EqualTo("First Routine!")); Assert.That(updatedRoutine2, Is.SameAs(routine2)); Assert.That(output2, Is.EqualTo("First Routine!Second Routine!")); } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("*** Test Failed ***"); sb.AppendLine(ex.ToString()); sb.AppendLine("*** Log: ***"); var log = _logWriter.ToString(); sb.AppendLine(log); Assert.Fail(sb.ToString()); } }
/// <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 async Task Routine_ReturnsFaultedTask_LogsFaultedTask() { // Arrange using IJobManager jobManager = TestHelper.CreateJobManager(true); var job = jobManager.Create("my-job"); var start = "2000-01-01Z".ToUtcDateOffset(); var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start); TimeProvider.Override(timeMachine); var output = new StringWriterWithEncoding(Encoding.UTF8); job.Output = output; var exception = new NotSupportedException("Bye baby!"); JobDelegate routine = (parameter, tracker, writer, token) => { writer.WriteLine("Hi there!"); return(Task.FromException(exception)); }; job.Schedule = new ConcreteSchedule( start.AddSeconds(1)); job.IsEnabled = true; // Act job.Routine = routine; var updatedRoutine = job.Routine; await timeMachine.WaitUntilSecondsElapse(start, 1.5); // will fail by this time var outputResult = output.ToString(); var info = job.GetInfo(null); // Assert try { Assert.That(updatedRoutine, Is.SameAs(routine)); Assert.That(outputResult, Does.Contain("Hi there!")); Assert.That(outputResult, Does.Contain(exception.ToString())); Assert.That(info.CurrentRun, Is.Null); Assert.That(info.RunCount, Is.EqualTo(1)); var run = info.Runs.Single(); Assert.That(run.Status, Is.EqualTo(JobRunStatus.Faulted)); Assert.That(run.Exception, Is.SameAs(exception)); Assert.That(run.Output, Does.Contain(exception.ToString())); var log = _logWriter.ToString(); Assert.That(log, Does.Contain($"Job 'my-job' completed synchronously. Reason of start was 'ScheduleDueTime'.")); } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("*** Test Failed ***"); sb.AppendLine(ex.ToString()); sb.AppendLine("*** Log: ***"); var log = _logWriter.ToString(); sb.AppendLine(log); Assert.Fail(sb.ToString()); } }
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(); }
private IEnumerable <KeyValuePair <string, string> > HandleSearch(IDictionary <string, string> sparams, User user, string deviceId) { var searchCriteria = new SearchCriteria(GetValueOrDefault(sparams, "SearchCriteria", "")); var sortCriteria = new SortCriteria(GetValueOrDefault(sparams, "SortCriteria", "")); var filter = new Filter(GetValueOrDefault(sparams, "Filter", "*")); // sort example: dc:title, dc:date // Default to null instead of 0 // Upnp inspector sends 0 as requestedCount when it wants everything int?requestedCount = null; int?start = 0; int requestedVal; if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requestedVal) && requestedVal > 0) { requestedCount = requestedVal; } int startVal; if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out startVal) && startVal > 0) { start = startVal; } var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, CloseOutput = false, OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment }; StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); int totalCount = 0; int provided = 0; using (XmlWriter writer = XmlWriter.Create(builder, settings)) { //writer.WriteStartDocument(); writer.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL); writer.WriteAttributeString("xmlns", "dc", null, NS_DC); writer.WriteAttributeString("xmlns", "dlna", null, NS_DLNA); writer.WriteAttributeString("xmlns", "upnp", null, NS_UPNP); //didl.SetAttribute("xmlns:sec", NS_SEC); DidlBuilder.WriteXmlRootAttributes(_profile, writer); var serverItem = GetItemFromObjectId(sparams["ContainerID"], user); var item = serverItem.Item; var childrenResult = (GetChildrenSorted(item, user, searchCriteria, sortCriteria, start, requestedCount)); totalCount = childrenResult.TotalRecordCount; provided = childrenResult.Items.Length; foreach (var i in childrenResult.Items) { if (i.IsDisplayedAsFolder) { var childCount = (GetChildrenSorted(i, user, searchCriteria, sortCriteria, null, 0)) .TotalRecordCount; _didlBuilder.WriteFolderElement(writer, i, null, item, childCount, filter); } else { _didlBuilder.WriteItemElement(_config.GetDlnaConfiguration(), writer, i, user, item, serverItem.StubType, deviceId, filter); } } writer.WriteFullEndElement(); //writer.WriteEndDocument(); } var resXML = builder.ToString(); return(new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("Result", resXML), new KeyValuePair <string, string>("NumberReturned", provided.ToString(_usCulture)), new KeyValuePair <string, string>("TotalMatches", totalCount.ToString(_usCulture)), new KeyValuePair <string, string>("UpdateID", _systemUpdateId.ToString(_usCulture)) }); }
/// <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="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().GetLocation(); } project.Validate(); lock (Compiler.AutoGeneration.WxsGenerationSynchObject) { var oldAlgorithm = AutoGeneration.CustomIdAlgorithm; try { WixEntity.ResetIdGenerator(false); AutoGeneration.CustomIdAlgorithm = project.CustomIdAlgorithm ?? AutoGeneration.CustomIdAlgorithm; 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 wix3Namespace = "http://schemas.microsoft.com/wix/2006/wi"; var wix4Namespace = "http://wixtoolset.org/schemas/v4/wxs"; var wixNamespace = Compiler.IsWix4 ? wix4Namespace : wix3Namespace; var doc = XDocument.Parse( @"<?xml version=""1.0"" encoding=""utf-8""?> " + $"<Wix xmlns=\"{wixNamespace}\" {extraNamespaces} " + @" > </Wix>"); doc.Root.Add(project.ToXml()); AutoElements.NormalizeFilePaths(doc, project.SourceBaseDir, EmitRelativePaths); project.InvokeWixSourceGenerated(doc); AutoElements.ExpandCustomAttributes(doc, project); 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); Compiler.OutputWriteLine("\n----------------------------------------------------------\n"); Compiler.OutputWriteLine("Wix project file has been built: " + file + "\n"); project.InvokeWixSourceSaved(file); if (WixSourceSaved != null) { WixSourceSaved(file); } return(file); } finally { AutoGeneration.CustomIdAlgorithm = oldAlgorithm; } } } }
/// <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(); } }