public void CreateXhtmlContent_Invoke_ReturnsExpected(string content)
        {
            TextSyndicationContent syndicationContent = SyndicationContent.CreateXhtmlContent(content);

            Assert.Empty(syndicationContent.AttributeExtensions);
            Assert.Equal(content, syndicationContent.Text);
            Assert.Equal("xhtml", syndicationContent.Type);
        }
Beispiel #2
0
        public SyndicationFeedFormatter CreateFeed()
        {
            // Create a new Syndication Feed.
            SyndicationFeed feed = new SyndicationFeed();

            feed.Generator       = "Pro C# 2008 Sample Feed Generator";
            feed.Language        = "en-us";
            feed.LastUpdatedTime = new DateTimeOffset(DateTime.Now);
            feed.Title           = SyndicationContent.CreatePlaintextContent("Formula1 results");
            feed.Categories.Add(new SyndicationCategory("Formula1"));

            feed.Authors.Add(new SyndicationPerson("*****@*****.**", "Christian Nagel", "http://www.christiannagel.com"));

            feed.Description = SyndicationContent.CreatePlaintextContent("Sample Formula 1");

            Formula1DataContext data = new Formula1DataContext();

            feed.Items = from racer in data.Racers
                         from raceResult in racer.RaceResults
                         where raceResult.Race.Date > new DateTime(2007, 1, 1) && raceResult.Position == 1
                         orderby raceResult.Race.Date
                         select new SyndicationItem()
            {
                Title   = SyndicationContent.CreatePlaintextContent(String.Format("G.P. {0}", raceResult.Race.Circuit.Country)),
                Content = SyndicationContent.CreateXhtmlContent(
                    new XElement("p",
                                 new XElement("h3", String.Format("{0}, {1}", raceResult.Race.Circuit.Country, raceResult.Race.Date.ToShortDateString())),
                                 new XElement("b", String.Format("Winner: {0} {1}", racer.Firstname, racer.Lastname))).ToString())
            };



            //List<SyndicationItem> items = new List<SyndicationItem>();

            //// Create a new Syndication Item.
            //SyndicationItem item = new SyndicationItem("An item", "Item content", null);
            //items.Add(item);
            //feed.Items = items;

            // Return ATOM or RSS based on query string
            // rss -> http://localhost:8731/Design_Time_Addresses/SyndicationService/Feed1/
            // atom -> http://localhost:8731/Design_Time_Addresses/SyndicationService/Feed1/?format=atom
            string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
            SyndicationFeedFormatter formatter = null;

            if (query == "atom")
            {
                formatter = new Atom10FeedFormatter(feed);
            }
            else
            {
                formatter = new Rss20FeedFormatter(feed);
            }

            return(formatter);
        }
Beispiel #3
0
        private SyndicationFeed GetAtomFeed(IApplicationConfiguration config)
        {
            //TODO: Make configurable
            var defaultAuthor = new SyndicationPerson
            {
                Name = "Michael Tyson",
                Uri  = config.BaseUrl + "/about"
            };

            var feedItems = db.Posts
                            .Select(p => {
                var lastWriteTime = File.GetLastWriteTime(Path.Combine(siteBasePath, p.FileLocation));

                var item = new SyndicationItem(
                    p.Title,
                    SyndicationContent.CreateXhtmlContent(p.Content),
                    new Uri(config.BaseUrl + p.Href),
                    p.Href,
                    new DateTimeOffset(lastWriteTime));

                item.PublishDate = new DateTimeOffset(p.Date);

                item.Authors.Add((p.AuthorName == null && p.AuthorUrl == null) ?
                                 defaultAuthor :
                                 new SyndicationPerson
                {
                    Name = p.AuthorName,
                    Uri  = (!p.AuthorUrl.StartsWith("http")) ?
                           config.BaseUrl + p.AuthorUrl :
                           p.AuthorUrl
                });

                return(item);
            });

            var feed = new SyndicationFeed(
                config.SiteTitle,
                config.SiteSubTitle,
                new Uri(config.BaseUrl),
                config.BaseUrl,
                feedItems.Max(i => i.LastUpdatedTime),
                feedItems);

            var feedAuthors = feedItems.SelectMany(i => i.Authors)
                              .GroupBy(a => a.Name)
                              .Select(g => g.FirstOrDefault());

            foreach (var author in feedAuthors)
            {
                feed.Authors.Add(author);
            }

            return(feed);
        }
Beispiel #4
0
        public static string GetFeed(QuickParameters quickParameters, string type)
        {
            string urlPrefix = System.Configuration.ConfigurationManager.AppSettings["HostName"] + HttpContext.Current.Request.ApplicationPath;

            UserDataContext udc = UserDataContext.GetUserDataContext();

            quickParameters.Udc         = udc;
            quickParameters.ObjectTypes = QuickParameters.GetDelimitedObjectTypeIDs(rssEngineConfig.ObjectTypes, ',');
            quickParameters.SortBy      = QuickSort.StartDate;
            //quickParameters.FromStartDate = DateTime.Now - new TimeSpan(rssEngineConfig.Days, 0, 0, 0);
            quickParameters.Amount   = rssEngineConfig.MaxItems;
            quickParameters.PageSize = rssEngineConfig.MaxItems;

            StringBuilder   sb;
            List <string>   titleSegments = new List <string>();
            SyndicationFeed feed          = new SyndicationFeed();

            if (quickParameters.CommunityID.HasValue)
            {
                DataObjectCommunity channelCommunity = DataObject.Load <DataObjectCommunity>(quickParameters.CommunityID);
                if (channelCommunity.State != ObjectState.Added)
                {
                    if (channelCommunity.ObjectType == Helper.GetObjectTypeNumericID("ProfileCommunity"))
                    {
                        titleSegments.Add(string.Format("Von {0}", channelCommunity.Nickname));
                    }
                    else
                    {
                        titleSegments.Add(string.Format("Von {0}", channelCommunity.Title));
                    }
                }
            }
            else if (quickParameters.UserID.HasValue)
            {
                Business.DataObjectUser channelUser = DataObject.Load <DataObjectUser>(quickParameters.UserID);
                if (channelUser.State != ObjectState.Added)
                {
                    titleSegments.Add(string.Format("Von {0}", channelUser.Nickname));
                }
            }
            if (!string.IsNullOrEmpty(quickParameters.RawTags1) || !string.IsNullOrEmpty(quickParameters.RawTags2) || !string.IsNullOrEmpty(quickParameters.RawTags3))
            {
                titleSegments.Add(string.Format("Tags {0}", Helper.GetTagWordString(new List <string>()
                {
                    quickParameters.RawTags1, quickParameters.RawTags2, quickParameters.RawTags3
                })));
            }

            sb = new StringBuilder();
            if (titleSegments.Count > 0)
            {
                for (int i = 0; i < titleSegments.Count; i++)
                {
                    sb.Append(titleSegments[i]);
                    if (i < titleSegments.Count - 1)
                    {
                        sb.Append(", ");
                    }
                }
            }
            else
            {
                sb.Append("Alles");
            }
            string title       = string.Format("{0} Feed - {1}", siteName, sb.ToString());
            string description = "RSS Feed von " + siteName;

            feed.Title       = TextSyndicationContent.CreatePlaintextContent(title);
            feed.Description = TextSyndicationContent.CreatePlaintextContent(description);
            feed.Links.Add(new SyndicationLink(new Uri(urlPrefix)));
            feed.Language = "de-CH";

            List <SyndicationItem>      items    = new List <SyndicationItem>();
            DataObjectList <DataObject> rssItems = DataObjects.Load <DataObject>(quickParameters);

            foreach (DataObject rssItem in rssItems)
            {
                SyndicationItem item = new SyndicationItem();

                // Add prefix to title
                item.Title = TextSyndicationContent.CreatePlaintextContent("[" + Helper.GetObjectName(rssItem.ObjectType, true) + "] " + rssItem.Title);

                // Set owner as author
                SyndicationPerson author = new SyndicationPerson();
                author.Name = rssItem.Nickname;
                item.Authors.Add(author);

                // Set object's guid
                item.Id = rssItem.objectID.Value.ToString();

                // Link to the object
                string itemUrl = urlPrefix + Helper.GetDetailLink(rssItem.ObjectType, rssItem.objectID.Value.ToString());
                item.AddPermalink(new Uri(itemUrl));

                // Take start date as publish date
                item.PublishDate = rssItem.StartDate;

                // Image if available
                if (!string.IsNullOrEmpty(rssItem.GetImage(PictureVersion.S)) && rssItem.GetImage(PictureVersion.S).ToLower() != Helper.GetDefaultURLImageSmall(rssItem.ObjectType).ToLower())
                {
                    item.Content = SyndicationContent.CreateXhtmlContent("<div><a href=\"" + itemUrl + "\"><img src=\"" + System.Configuration.ConfigurationManager.AppSettings["MediaDomainName"] + rssItem.GetImage(PictureVersion.S) + "\"></a></div><div>" + rssItem.Description.StripHTMLTags().CropString(rssEngineConfig.MaxDescriptionLength) + "</div>");
                }
                else
                {
                    item.Content = TextSyndicationContent.CreatePlaintextContent(rssItem.Description.StripHTMLTags().CropString(rssEngineConfig.MaxDescriptionLength));
                }

                items.Add(item);
            }

            feed.Items = items;

            sb = new StringBuilder();
            XmlWriter xmlWriter = XmlWriter.Create(sb);

            if (type == "rss")
            {
                feed.SaveAsRss20(xmlWriter);
            }
            else if (type == "atom")
            {
                feed.SaveAsAtom10(xmlWriter);
            }
            xmlWriter.Close();

            string feedXml = sb.ToString();

            feedXml = Regex.Replace(feedXml, @"^<.*?xml.*?>\s*", "");
            return(feedXml);
        }
        public SyndicationFeedFormatter CreateFeed()
        {
            DateTime fromDate = DateTime.Today - TimeSpan.FromDays(365);
            DateTime toDate   = DateTime.Today;
            string   from     = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["from"];
            string   to       = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["to"];

            if (from != null && to != null)
            {
                try
                {
                    fromDate = DateTime.Parse(from);
                    toDate   = DateTime.Parse(to);
                }
                catch (FormatException)
                {
                    // keep the default dates
                }
            }

            // Create a new Syndication Feed.
            var feed = new SyndicationFeed();

            feed.Generator       = "";
            feed.Generator       = "Pro C# 4.0 Sample Feed Generator";
            feed.Language        = "en-us";
            feed.LastUpdatedTime = new DateTimeOffset(DateTime.Now);
            feed.Title           = SyndicationContent.CreatePlaintextContent("Formula1 results");
            feed.Categories.Add(new SyndicationCategory("Formula1"));
            feed.Authors.Add(new SyndicationPerson("*****@*****.**",
                                                   "Christian Nagel", "http://www.christiannagel.com"));
            feed.Description = SyndicationContent.CreatePlaintextContent(
                "Sample Formula 1");


            using (var data = new Formula1Entities())
            {
                var races = (from racer in data.Racers
                             from raceResult in racer.RaceResults
                             where raceResult.Race.Date > fromDate &&
                             raceResult.Race.Date < toDate &&
                             raceResult.Position == 1
                             orderby raceResult.Race.Date
                             select new
                {
                    Country = raceResult.Race.Circuit.Country,
                    Date = raceResult.Race.Date,
                    Winner = racer.Firstname + " " + racer.Lastname
                }).ToArray();


                feed.Items = races.Select(race =>
                {
                    return(new SyndicationItem
                    {
                        Title = SyndicationContent.CreatePlaintextContent(
                            String.Format("G.P. {0}", race.Country)),
                        Content = SyndicationContent.CreateXhtmlContent(
                            new XElement("p",
                                         new XElement("h3", String.Format("{0}, {1}",
                                                                          race.Country, race.Date.ToShortDateString())),
                                         new XElement("b", String.Format("Winner: {0}", race.Winner))).ToString())
                    });
                });



                // Return ATOM or RSS based on query string
                // rss -> http://localhost:8732/Design_Time_Addresses/SyndicationService/Feed1/
                // atom -> http://localhost:8732/Design_Time_Addresses/SyndicationService/Feed1/?format=atom
                string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
                SyndicationFeedFormatter formatter = null;
                if (query == "atom")
                {
                    formatter = new Atom10FeedFormatter(feed);
                }
                else
                {
                    formatter = new Rss20FeedFormatter(feed);
                }


                return(formatter);
            }
        }
Beispiel #6
0
        public async virtual Task <ActionResult> Feed()
        {
            var entries = await this.repository.BlogEntries
                          .Include(b => b.Tags)
                          .AsNoTracking()
                          .Where(b => b.Visible && b.PublishDate <= DateTime.Now)
                          .OrderByDescending(b => b.PublishDate)
                          .ToArrayAsync();

            string baseUrl = this.Request.Url.GetLeftPart(UriPartial.Authority);

            var feed = new SyndicationFeed(
                ConfigurationManager.AppSettings["BlogName"],
                ConfigurationManager.AppSettings["BlogDescription"],
                new Uri(this.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action(MVC.Blog.Feed())));

            feed.BaseUri = new Uri(baseUrl);

            if (entries.Any())
            {
                DateTime createdDate = entries.First().PublishDate;

                DateTime?lastModifiedDate = entries.OrderByDescending(e => e.Modified).First().Modified;
                if (lastModifiedDate.HasValue && lastModifiedDate.Value > createdDate)
                {
                    feed.LastUpdatedTime = lastModifiedDate.Value;
                }
                else
                {
                    feed.LastUpdatedTime = createdDate;
                }
            }

            var feedItems = new List <SyndicationItem>();

            foreach (var blogEntry in entries)
            {
                var syndicationItem = new SyndicationItem(
                    blogEntry.Header,
                    SyndicationContent.CreateXhtmlContent(blogEntry.ShortContent + blogEntry.Content),
                    new Uri(baseUrl + Url.Action(blogEntry.Url)),
                    blogEntry.Id.ToString(),
                    blogEntry.Modified.HasValue ? blogEntry.Modified.Value : blogEntry.PublishDate);

                if (!string.IsNullOrEmpty(blogEntry.Author))
                {
                    syndicationItem.Authors.Add(new SyndicationPerson()
                    {
                        Name = blogEntry.Author
                    });
                }

                foreach (var tag in blogEntry.Tags)
                {
                    syndicationItem.Categories.Add(new SyndicationCategory(tag.Name));
                }

                feedItems.Add(syndicationItem);
            }

            feed.Items = feedItems;

            return(new Palmmedia.Common.Net.Mvc.Feed.RssSyndicationFeedActionResult(feed));
        }
Beispiel #7
0
        public SyndicationFeedFormatter CreateFeed()
        {
            DateTime            fromDate = DateTime.Today - TimeSpan.FromDays(365);
            DateTime            toDate   = DateTime.Today;
            WebOperationContext context  = WebOperationContext.Current;

            if (context == null)
            {
                return(null);
            }

            string frm = context.IncomingRequest.UriTemplateMatch.QueryParameters["from"];
            string to  = context.IncomingRequest.UriTemplateMatch.QueryParameters["to"];

            if (frm != null && to != null)
            {
                try
                {
                    fromDate = DateTime.Parse(frm);
                    toDate   = DateTime.Parse(to);
                }
                catch (FormatException)
                {
                    // Оставляем значения по-умолчанию
                }
            }

            // Создаем синдицируемый канал
            var feed = new SyndicationFeed
            {
                Generator       = "Pro C# 4.0 Sample Feed Generator",
                Language        = "en-us",
                LastUpdatedTime = new DateTimeOffset(DateTime.Now),
                Title           = SyndicationContent.CreatePlaintextContent("Formula1 results")
            };

            feed.Categories.Add(new SyndicationCategory("Formula1"));
            feed.Authors.Add(
                new SyndicationPerson("*****@*****.**", "Christian Nagel", "http://www.christiannagel.com"));
            feed.Description = SyndicationContent.CreatePlaintextContent("Sample Formula 1");

            // Заполняем значения синдикации
            using (var entities = new Formula(ConfigurationManager.ConnectionStrings["FormulaEntities"].ConnectionString))
            {
                var racers = (from racer in entities.Racers
                              from raceResult in racer.RaceResults
                              where raceResult.Race.Date > fromDate && raceResult.Race.Date < toDate && raceResult.Position == 1
                              orderby raceResult.Race.Date
                              select new
                {
                    raceResult.Race.Circuit.Country,
                    raceResult.Race.Date,
                    Winner = racer.Firstname + " " + racer.Lastname
                }).ToArray();

                feed.Items = racers.Select(race => new SyndicationItem
                {
                    Title   = SyndicationContent.CreatePlaintextContent(string.Format("G.P. {0}", race.Country)),
                    Content = SyndicationContent.CreateXhtmlContent(
                        new XElement("p",
                                     new XElement("h3", string.Format("{0}, {1}", race.Country, race.Date.ToShortDateString())),
                                     new XElement("b", string.Format("Winner: {0}", race.Winner))).ToString())
                });

                // Определяем формат возвращаемых данных
                string format = context.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
                return(format == "atom"
               ? (SyndicationFeedFormatter) new Atom10FeedFormatter(feed)
               : new Rss20FeedFormatter(feed));
            }
        }