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 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();
        }
		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;
		}
    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;
    }
示例#5
0
    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;
            }
    }
示例#6
0
        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);
        }
示例#7
0
文件: YAMJ.cs 项目: rsanch1/YANFOE.v2
        /// <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));
            }
        }
示例#8
0
文件: YAMJ.cs 项目: rsanch1/YANFOE.v2
        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();
            }
        }
示例#9
0
文件: YAMJ.cs 项目: rsanch1/YANFOE.v2
        /// <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));
            }
        }
示例#10
0
文件: XBMC.cs 项目: rsanch1/YANFOE.v2
        /// <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));
            }
        }
示例#11
0
 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 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);
            }
        }
示例#13
0
        /// <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();
            }
        }
示例#14
0
文件: XBMC.cs 项目: rsanch1/YANFOE.v2
        /// <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));
            }
        }
示例#15
0
        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();
            }
        }
示例#16
0
文件: Compiler.cs 项目: Eun/WixSharp
        /// <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;
        }
示例#17
0
        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);
        }
示例#18
0
        /// <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;
            }
        }
示例#19
0
文件: YAMJ.cs 项目: rsanch1/YANFOE.v2
        /// <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();
            }
        }
示例#20
0
        /// <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;
        }
示例#21
0
文件: XBMC.cs 项目: rsanch1/YANFOE.v2
        /// <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();
            }
        }