Example #1
0
 public void TransformFeed(SyndicationFeed feed, SyndicationVisitorContext context)
 {
     if (feed.Links.Any())
     {
         feed.Links[0] = new SyndicationLink(context.RssUrl, "alternate", title: null, mediaType: null, length: 0);
     }
 }
Example #2
0
        public async Task<IHttpActionResult> GetService(string id)
        {
            Service service = await db.Services.FindAsync(id);
            if (service == null)
            {
                return NotFound();
            }

            var ServiceFeed = new SyndicationFeed();
            ServiceFeed.Id = service.Id;
            ServiceFeed.LastUpdatedTime = service.Updated;
            ServiceFeed.Title = new TextSyndicationContent(service.Title);
            ServiceFeed.Description = new TextSyndicationContent(service.Summary);

            ServiceFeed.Categories.Add(new SyndicationCategory(service.ServiceCategoryId.ToString(), null, service.Category.Name));

            var SelfLink = new SyndicationLink();
            SelfLink.RelationshipType = "self";
            SelfLink.Uri = new Uri(Url.Content("~/Service/" + service.Id));
            SelfLink.MediaType = "application/atom+xml";
            ServiceFeed.Links.Add(SelfLink);

            var HtmlLink = new SyndicationLink();
            HtmlLink.RelationshipType = "self";
            HtmlLink.Uri = new Uri("http://surreyhillsdc.azurewebsites.net/");
            HtmlLink.MediaType = "text/html";
            ServiceFeed.Links.Add(HtmlLink);

            return Ok(ServiceFeed.GetAtom10Formatter());
        }
        /// <summary>
        /// Turn a SimpleFeed object into a SyndicationFeed object
        /// </summary>
        private SyndicationFeed GetSyndicationFeed(SimpleFeed pFeed)
        {
            var feed = new SyndicationFeed();
            var items = new List<SyndicationItem>();

            feed.BaseUri = new Uri(pFeed.BaseUrl);
            if (!string.IsNullOrWhiteSpace(pFeed.Title))
                feed.Title = new TextSyndicationContent(pFeed.Title);
            if (!string.IsNullOrWhiteSpace(pFeed.Description))
                feed.Description = new TextSyndicationContent(pFeed.Description);
            if (!string.IsNullOrWhiteSpace(pFeed.Language))
                feed.Language = pFeed.Language;

            if (pFeed.Entries != null)
            {
                foreach (var entry in pFeed.Entries)
                {
                    var item = new SyndicationItem(entry.Title, entry.Body, entry.TitleLinkUri);
                    //Id, DatePublished, DateLastUpdated are required so that each new post won't make readers think that every entry is new
                    item.Id = entry.Id;
                    item.PublishDate = entry.DatePublished;
                    item.LastUpdatedTime = entry.DateLastUpdated;
                    item.BaseUri = entry.TitleLinkUri;
                    items.Add(item);
                }
            }

            feed.Items = items;
            return feed;
        }
        public ActionResult ActivityFeed(string name, int id)
        {
            var polfeed = _polRep.LatestFeed(id, includeposts);
            List<SyndicationItem> items = new List<SyndicationItem>();
            var pol = _polRep.GetPoliticianById(id);
            var polLink = this.Request.Url.GetLeftPart(UriPartial.Authority) + pol.PolLink(this);

            SyndicationFeed feed =
                new SyndicationFeed(
                        String.Format("{0} Feed", pol.FullName()), "Activity Feed på Folkets Ting",
                        new Uri(Request.Url.ToString()),
                        Request.Url.AbsoluteUri,
                        polfeed.Last().date);

            foreach (var feeditem in polfeed)
            {
                var link = (this.Request.Url.GetLeftPart(UriPartial.Authority) + feeditem.ActionUrl);
                SyndicationItem item =
                    new SyndicationItem(feeditem.ActionText,
                                    feeditem.BodyText,
                                    new Uri(link),
                                    feeditem.ActionUrl + feeditem.ActionText,
                                    feeditem.date);
                items.Add(item);
            }
            feed.Items = items;

            return new RssActionResult() { Feed = feed };
        }
        public GlobalEquityWindow()
        {
            this.InitializeComponent();

            Image img = Properties.Resources.standardandpoors;
            this.logoBox.Image = img;

            this.dataExtraction = new DataExtraction();
            this.feedCondent = new SyndicationFeed();
            this.links = new Dictionary<DateTime, string>();

            this.feedCondent = this.dataExtraction.GetRssFeedData("https://us.spindices.com/rss/rss-details/?rssFeedName=global-equity");
            if (this.feedCondent != null)
            {
                Tuple<DataGridView, Dictionary<DateTime, string>> parsedContent =
                    this.dataExtraction.ParseRssFeedData(this.feedCondent);

                foreach (DataGridViewRow row in parsedContent.Item1.Rows)
                {
                    int rowId = this.dataGridContent.Rows.Add();
                    this.dataGridContent.Rows[rowId].Cells[0].Value = row.Cells[0].Value;
                    this.dataGridContent.Rows[rowId].Cells[1].Value = row.Cells[1].Value;
                    this.dataGridContent.Rows[rowId].Cells[2].Value = row.Cells[2].Value;
                }

                this.links = parsedContent.Item2;
            }

            this.dataGridContent.Sort(this.dataGridContent.Columns[0], ListSortDirection.Descending);
        }
        public string Build(FeedData dataFeed, Uri baseUri)
        {
            var feed = new SyndicationFeed
            {
                Id = dataFeed.Id.ToString(),
                LastUpdatedTime = dataFeed.DateCreated,
                Items = dataFeed.Messages.Select(x => new SyndicationItem
                {
                    Content = new RawSyndicationContent(x.Body),
                    Id = x.Id.ToString(),
                    LastUpdatedTime = x.CreatedAt
                })
            };

            if (!string.IsNullOrEmpty(dataFeed.NextUri))
                feed.Links.Add(new SyndicationLink(new Uri(baseUri, dataFeed.NextUri), NextInArchiveRelationshipType,
                    "Next In Archive", ContentType, 0));

            if (!string.IsNullOrEmpty(dataFeed.PreviousUri))
                feed.Links.Add(new SyndicationLink(new Uri(baseUri, dataFeed.PreviousUri), PrevInArchiveRelationshipType,
                    "Previous In Archive", ContentType, 0));

            var formatter = new Atom10FeedFormatter(feed);

            var sw = new StringWriter();
            using (var writer = XmlWriter.Create(sw))
            {
                formatter.WriteTo(writer);
            }

            return sw.ToString();
        }
Example #7
0
        public SyndicationFeedFormatter CreateFeed()
        {
            // Create a new Syndication Feed.
            SyndicationFeed feed = new SyndicationFeed("Feed Title", "A WCF Syndication Feed", null);
            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:8733/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/
            // atom -> http://localhost:8733/Design_Time_Addresses/SyndicationServiceLibrary1/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;
        }
Example #8
0
        public SyndicationFeedFormatter CreateFeed()
        {
            // Créez un flux RSS.
            SyndicationFeed feed = new SyndicationFeed("Bug Track", "Flux rss du bug track", null);
            List<SyndicationItem> items = new List<SyndicationItem>();

            // Créez un article RSS.
            List<DBO.Bug> bugs = DataAccess.Bug.GetLastBug(10);
            bugs.ForEach(bug => items.Add(new SyndicationItem(bug.Title, bug.Details, null)));

            feed.Items = items;

            // Renvoie ATOM ou RSS en fonction de la chaîne de requête
            // rss -> http://localhost:8733/Design_Time_Addresses/SyndicationServiceBugTrack/Feed1/
            // atom -> http://localhost:8733/Design_Time_Addresses/SyndicationServiceBugTrack/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;
        }
        public SyndicationFeedActionResult(SyndicationFeed result)
        {
            if (result == null)
                throw new ArgumentNullException("result");

            Result = result;
        }
Example #10
0
        public SyndicationFeedFormatter CreateFeed()
        {
            // Créez un flux RSS.
            SyndicationFeed feed = new SyndicationFeed("TekConf Event", "Last 10 event added in TekConf", null);
            List<SyndicationItem> items = TekConf.DataAccess.Event.GetLastEventsList(10).Select(
                e => new SyndicationItem("idEvent :  " + e.id + " : " + e.name,
                    e.location + ", " + e.time + " \n " + e.Technology + " \n " + e.description,
                    null)
                ).ToList();
            feed.Items = items;

            // Renvoie ATOM ou RSS en fonction de la chaîne de requête
            // rss -> http://localhost:8733/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/
            // atom -> http://localhost:8733/Design_Time_Addresses/SyndicationServiceLibrary1/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;
        }
Example #11
0
		internal override void WriteXml(XmlWriter writer, SyndicationFeed feed)
		{
			writer.WriteStartElement(FeedName, FeedNamespace);

			if (!String.IsNullOrEmpty(feed.Language))
					writer.WriteAttributeString("xml:lang", feed.Language);

			WriteXml(writer, feed.Title, "title", true);
			writer.WriteElementString("id", feed.Id);
			WriteXml(writer, feed.Copyright, "rights");

			string updated = feed.LastUpdatedTime.ToUniversalTime().ToString("s");
			writer.WriteElementString("updated", updated + "Z");

			if (feed.ImageUrl != null)
				writer.WriteElementString("logo", feed.ImageUrl.ToString());

			if (!String.IsNullOrEmpty(feed.Generator))
				writer.WriteElementString("generator", feed.Generator);

			WriteXml(writer, feed.Description, "summary");

			foreach (SyndicationItem item in feed.Items)
				{
					WriteTo(writer, item);
				}

			writer.WriteEndElement();
		}
Example #12
0
		/// <summary>
		/// Executes the syndication result on the given context.
		/// </summary>
		/// <param name="context">The current context.</param>
		public virtual void Write(IStreamResponse response) {
			var writer = new XmlTextWriter(response.OutputStream, Encoding.UTF8);
			var ui = new Client.Helpers.UIHelper();

			// Write headers
			response.ContentType = ContentType;
			response.ContentEncoding = Encoding.UTF8;

			var feed = new SyndicationFeed() { 
				Title = new TextSyndicationContent(Config.Site.Title),
				LastUpdatedTime = Posts.First().Published.Value,
				Description = new TextSyndicationContent(Config.Site.Description),
			};
			feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(App.Env.AbsoluteUrl("~/"))));

			var items = new List<SyndicationItem>();
			foreach (var post in Posts) {
				var item = new SyndicationItem() { 
					Title = SyndicationContent.CreatePlaintextContent(post.Title),
					PublishDate = post.Published.Value,
					Summary = SyndicationContent.CreateHtmlContent(post.Body)
				};
				item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(App.Env.AbsoluteUrl("~/" + post.Type.Slug + "/" + post.Slug))));
				items.Add(item);
			}
			feed.Items = items;

			var formatter = GetFormatter(feed);
			formatter.WriteTo(writer);

			writer.Flush();
			writer.Close();
		}
Example #13
0
        public ActionResult Rss(string domain="")
        {
            var news = NewsProvider.GetSeason(2014, domain).OrderByDescending(n=>n.Date).Take(10);

            var feedItems = new List<SyndicationItem>();
            foreach (var news_item in news)
            {
                var item = new SyndicationItem()
                {
                    Title = TextSyndicationContent.CreatePlaintextContent(news_item.Title),
                    PublishDate = new DateTimeOffset(news_item.Date),
                    Summary = TextSyndicationContent.CreateHtmlContent(CombineBriefWithImage(news_item)),
                };
                string url = "http://afspb.org.ru/news/" + news_item.Slug;

                var link = new SyndicationLink(new Uri(url));
                link.Title = "Перейти к новости";
                item.Links.Add(link);
                feedItems.Add(item);
            }

            var feed = new SyndicationFeed(
                    "Новости сайта Автомобильной Федерации Санкт-Петербурга и Ленинградской области",
                    "",
                    new Uri("http://afspb.org.ru/news/Rss"),
                    feedItems);

            return new RssResult()
            {
                Feed = feed
            };
        }
Example #14
0
        public SyndicationFeedFormatter CreateFeedForBlog(string user, string blog)
        {
            SyndicationFeed feed = new SyndicationFeed("Blog feed", "A feed linked to a blog", null);
            List<SyndicationItem> items = new List<SyndicationItem>();
            List<Dbo.RssArticle> articles = BusinessManagement.Feed.GetBlogContent(user, blog);

            foreach (Dbo.RssArticle article in articles)
            {
                SyndicationItem item = new SyndicationItem(article.Title, article.Content, null);
                item.PublishDate = article.CreationDate;
                items.Add(item);
            }
            feed.Items = items;

            // Renvoie ATOM ou RSS en fonction de la chaîne de requête
            // rss -> http://localhost:8733/Design_Time_Addresses/FluxRss/Feed1/
            // atom -> http://localhost:8733/Design_Time_Addresses/FluxRss/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;
        }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the FeedActionResult class
        /// </summary>
        /// <param name="blogName">Name of the blog</param>
        /// <param name="description">Feed description</param>
        /// <param name="format">Format of the feed</param>
        /// <param name="url">A URL Helper</param>
        /// <param name="posts">The posts to include in the feed</param>
        public FeedActionResult(string blogName, string description, FeedFormat format, UrlHelper url, IEnumerable<BlogPost> posts)
        {
            Guid blogPostId;
            string postRelative;
            SyndicationItem item;
            List<SyndicationItem> items = new List<SyndicationItem>();

            // Specify the type of feed
            Format = format;

            // Initialize the current feed
            Feed = new SyndicationFeed(blogName, description, new Uri(url.RouteUrl("Default"), UriKind.Relative));

            //load the posts as items
            foreach (BlogPost post in posts)
            {
                blogPostId = post.BlogPostId;
                postRelative = url.Action(
                    "Details", "Posts",
                    new
                    {
                        year = post.PostedDate.Value.Year,
                        month = post.PostedDate.Value.Month,
                        day = post.PostedDate.Value.Day,
                        id = blogPostId
                    });

                item = new SyndicationItem(post.Title, post.Post,
                    new Uri(postRelative, UriKind.Relative), post.BlogPostId.ToString(), post.PostedDate.Value);

                items.Add(item);
            }

            Feed.Items = items.OrderByDescending(x => x.LastUpdatedTime);
        }
Example #16
0
        public SyndicationFeedFormatter GetProcesses(string format)
        {
            IEnumerable<Process> processes = new List<Process>( Process.GetProcesses() );

            //SyndicationFeed also has convenience constructors
            //that take in common elements like Title and Content.
            SyndicationFeed f = new SyndicationFeed();            

            
            f.LastUpdatedTime = DateTimeOffset.Now;
            f.Title = SyndicationContent.CreatePlaintextContent("Currently running processes");
            f.Links.Add(SyndicationLink.CreateSelfLink(OperationContext.Current.IncomingMessageHeaders.To));

            f.Items = from p in processes
                      select new SyndicationItem()
                      {
                          LastUpdatedTime = DateTimeOffset.Now,
                          Title = SyndicationContent.CreatePlaintextContent(p.ProcessName),
                          Summary = SyndicationContent.CreateHtmlContent(String.Format("<b>{0}</b>", p.MainWindowTitle)),
                          Content = SyndicationContent.CreateXmlContent(new ProcessData(p))
                      };

            
            // Choose a formatter according to the query string passed.
            if (format == "rss")
            {
                return new Rss20FeedFormatter(f);
            }
            else
            {
                return new Atom10FeedFormatter(f);
            }
        }
Example #17
0
        public SyndicationFeedFormatter CreateFeed()
        {
            // Create a new Syndication Feed.
            SyndicationFeed feed = new SyndicationFeed("Bug Track", "Flux rss du bug track", null);
            List<SyndicationItem> items = new List<SyndicationItem>();

            // Create a new Syndication Item.

            List<DBO.Bug> list = BusinessManagement.Bug.GetLastBug(10);

            foreach (DBO.Bug itemBug in list)
            {
                SyndicationItem item = new SyndicationItem(itemBug.ProjectName + " : " + itemBug.Title, itemBug.CreateDate + " \n " + itemBug.Details, null);
                items.Add(item);
            }

            feed.Items = items;

            // Return ATOM or RSS based on query string
            // rss -> http://localhost:8731/Design_Time_Addresses/SyndicationServiceBugTrack/Feed1/
            // atom -> http://localhost:8731/Design_Time_Addresses/SyndicationServiceBugTrack/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;
        }
        /// <summary>
        /// Normalizes a SyndicationItem into a FeedItem.
        /// </summary>
        /// <param name="feed">The <see cref="SyndicationFeed"/> on which the item was retrieved.</param>
        /// <param name="item">A <see cref="SyndicationItem"/> to normalize into a <see cref="FeedItem"/>.</param>
        /// <returns>Returns a normalized <see cref="FeedItem"/>.</returns>
        public virtual FeedItem Normalize(SyndicationFeed feed, SyndicationItem item)
        {
            var alternatelink = item.Links.FirstOrDefault(l => l.RelationshipType == null || l.RelationshipType.Equals("alternate", StringComparison.OrdinalIgnoreCase));

            Uri itemuri = null;
            Uri parsed;
            if (alternatelink == null && !Uri.TryCreate(item.Id, UriKind.Absolute, out parsed))
            {
                itemuri = parsed;
            }
            else
            {
                itemuri = alternatelink.GetAbsoluteUri();
            }

            return new FeedItem
            {
                Id = string.IsNullOrEmpty(item.Id) ? null : item.Id.Trim(),
                Title = item.Title == null ? null : Normalize(item.Title.Text),
                Content = item.Content == null ? null : Normalize(((TextSyndicationContent)item.Content).Text),
                Summary = item.Summary == null ? null : Normalize(item.Summary.Text),
                PublishDate = item.PublishDate,
                LastUpdatedDate = item.LastUpdatedTime == DateTimeOffset.MinValue ? item.PublishDate : item.LastUpdatedTime,
                Uri = itemuri
            };
        }
        public ActionResult NewsRssFeed()
        {
            var latestNews = Umbraco.TypedContentAtXPath("//ulgNewsItem").Where(x => x.IsVisible()).OrderByDescending(x => x.GetPropertyValue<DateTime>("articleDate")).Take(20);

            var lastUpdate = (from news in latestNews
                              select news.UpdateDate).Max();
            SyndicationFeed feed =
                     new SyndicationFeed("Local Government Starter Kit News RSS Feed Example",
                                         "Latest News for Local Government Starter Kit site",
                                         new Uri("http://www.uLocalGov.co.uk"),
                                         "uLocalCovNews",
                                         lastUpdate);

            List<SyndicationItem> items = new List<SyndicationItem>();
            foreach (var newsItem in latestNews)
            {
                string itemTitle = string.Format("{0}", newsItem.GetPropertyValue("title"));
                   Uri itemURI = new Uri(newsItem.UrlWithDomain());
                string itemContent = string.Format("<p>{0:dddd, MM yyyy} - {1}</p>", newsItem.GetPropertyValue<DateTime>("articleDate"), newsItem.GetPropertyValue("newsSummary"));
                SyndicationItem item =
                    new SyndicationItem(itemTitle,
                                        itemContent,
                                        itemURI,
                                        newsItem.Id.ToString(),
                                        newsItem.UpdateDate);

                items.Add(item);
            }
            feed.Items = items;
            return new RssActionResult(feed);
        }
Example #20
0
        public ActionResult News()
        {
            var items = _newsService.GetAllGeneric<NewsRssFeedViewModel>()
                .OrderByDescending(m => m.CreatedOn)
                .Take(30)
                .ToList()
                .Select(m => new SyndicationItem
                {
                    Title = new TextSyndicationContent(m.Title),
                    Summary = new TextSyndicationContent(m.Summary),
                    Content = new TextSyndicationContent(m.Description),
                    PublishDate = m.CreatedOn,
                    Id = m.Id.ToString(),
                    BaseUri = new Uri(Url.AbsoluteAction("Details", "News", new { id = m.Id })),
                })
                .ToList();

            var feed = new SyndicationFeed(CommonSettings.SiteDefaultTitle,
                CommonSettings.SiteDefaultDescription,
                null,
                Guid.NewGuid().ToString(),
                DateTime.Now);
            feed.Items = items;

            return new RssActionResult { Feed = feed };
        }
Example #21
0
        public MarketNewsWindow()
        {
            this.InitializeComponent();

            Image img = Properties.Resources.wsj;
            this.logoBox.Image = img;

            this.dataExtraction = new DataExtraction();
            this.feedCondent = new SyndicationFeed();
            this.links = new Dictionary<DateTime, string>();

            this.feedCondent = this.dataExtraction.GetRssFeedData("http://online.wsj.com/xml/rss/3_7031.xml");
            if (this.feedCondent != null)
            {
                Tuple<DataGridView, Dictionary<DateTime, string>> parsedContent =
                    this.dataExtraction.ParseRssFeedData(this.feedCondent);

                foreach (DataGridViewRow row in parsedContent.Item1.Rows)
                {
                    int rowId = this.dataGridContent.Rows.Add();
                    this.dataGridContent.Rows[rowId].Cells[0].Value = row.Cells[0].Value;
                    this.dataGridContent.Rows[rowId].Cells[1].Value = row.Cells[1].Value;
                    this.dataGridContent.Rows[rowId].Cells[2].Value = row.Cells[2].Value;
                }

                this.links = parsedContent.Item2;
            }

            this.dataGridContent.Sort(this.dataGridContent.Columns[0], ListSortDirection.Descending);
        }
Example #22
0
        protected override void WriteFile(System.Web.HttpResponseBase response)
        {
            var items = new List<SyndicationItem>();

            foreach (Dinner d in this.Dinners)
            {
                string contentString = String.Format("{0} with {1} on {2:MMM dd, yyyy} at {3}. Where: {4}, {5}",
                            d.Description, d.HostedBy, d.EventDate, d.EventDate.ToShortTimeString(), d.Address, d.Country);

                var item = new SyndicationItem(
                    title: d.Title,
                    content: contentString,
                    itemAlternateLink: new Uri("http://nrddnr.com/" + d.DinnerID),
                    id: "http://nrddnr.com/" + d.DinnerID,
                    lastUpdatedTime: d.EventDate.ToUniversalTime()
                    );
                item.PublishDate = d.EventDate.ToUniversalTime();
                item.Summary = new TextSyndicationContent(contentString, TextSyndicationContentKind.Plaintext);
                items.Add(item);
            }

            SyndicationFeed feed = new SyndicationFeed(
                this.Title,
                this.Title, /* Using Title also as Description */
                currentUrl,
                items);

            Rss20FeedFormatter formatter = new Rss20FeedFormatter(feed);

            using (XmlWriter writer = XmlWriter.Create(response.Output))
            {
                formatter.WriteTo(writer);
            }
        }
        public SyndicationFeed CreateSyndicationFeed(string nickname, string feedType, string scheme, string host)
        {
            IList<Post> posts = _postRepository.GetBlogPosts(nickname);
            Blog blog = _blogRepository.GetBlog(nickname);
            
            string url = string.Format("{0}://{1}/{2}", scheme, host, nickname);
            var feed = new SyndicationFeed(blog.Title, blog.Description, new Uri(url), url, blog.LastUpdated);
            feed.Authors.Add(new SyndicationPerson {Name = blog.User.Name});
            
            feed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(url + "/feed/" + feedType)));

            var items = new List<SyndicationItem>();
            foreach (Post post in posts)
            {
                var htmlurl = string.Format("{0}://{1}/{2}/{3}/{4}/{5}/{6}", scheme, host, nickname, post.Posted.Year,
                                    post.Posted.Month, post.Posted.Day, post.TitleLink);

                var item = new SyndicationItem();
                item.Title = new TextSyndicationContent(post.Title, TextSyndicationContentKind.Html);
                item.Content = new TextSyndicationContent(post.BlogPost, TextSyndicationContentKind.Html);
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(htmlurl), "text/html"));
                
                var editurl = string.Format("{0}://{1}/{2}/pub/atom/{3}", scheme, host, nickname, post.Id);
                item.Links.Add(SyndicationLink.CreateSelfLink(new Uri(editurl)));
                item.Links.Add(new SyndicationLink { RelationshipType = "edit", Uri = new Uri(editurl), MediaType = "application/atom+xml;type=entry" });

                item.PublishDate = post.Edited;
                item.Id = editurl;
                items.Add(item);                
            }
            feed.Items = items;
            return feed;
        }
Example #24
0
 public SyndicationFeed GenerateFeeds(int noOfFeeds)
 {
     var feed = new SyndicationFeed
     {
         Title = new TextSyndicationContent("A simple rss feeder."),
         Language = "en-us",
         LastUpdatedTime = DateTime.Now,
         Copyright = new TextSyndicationContent("RRiwaj"),
         Description = new TextSyndicationContent("This is a simple rss feeder created using WCF Syndication class."),
         ImageUrl = new Uri("/Contents/Images/rss.png", UriKind.Relative),
     };
     var itemsRepo = _feedRepository.GetFeedItems(noOfFeeds); // Get Item Feeds from feed repository.
     var feedItems = new List<SyndicationItem>(); // Create new Syndication Item List which will be added to Syndication Feed
     foreach (var proxyItem in itemsRepo)
     {
         var item = new SyndicationItem
         {
             Title = SyndicationContent.CreatePlaintextContent(proxyItem.Title),
             PublishDate = proxyItem.FeedDate,
             Summary = SyndicationContent.CreateHtmlContent(proxyItem.Summary)
         };
         var authInfo = new SyndicationPerson
         {
             Name = proxyItem.AuthorName,
             Email = proxyItem.AuthorEmail
         };
         item.Authors.Add(authInfo);
         item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(proxyItem.FeedUrl)));
         feedItems.Add(item);
     }
     feed.Items = feedItems;
     return feed;
 }
Example #25
0
        /// <summary>
        /// Create the feed 
        /// </summary>
        /// <returns>The created feed</returns>
        public override SyndicationFeed ToFeed()
        {
            SyndicationFeed feed = new SyndicationFeed(Title, Title, new Uri(Uri), Id, DateTime.Parse(Updated.At));
            //feed.Authors.Add(new SyndicationPerson("[email protected]"));
            feed.Categories.Add(new SyndicationCategory(Title));
            feed.Description = new TextSyndicationContent(Title);

            List<SyndicationItem> items = new List<SyndicationItem>();
            if (commentList != null && commentList.comments != null)
            {
                for (int i = 0; i < commentList.comments.Count; i++)
                {
                    SyndicationItem item = new SyndicationItem(
                    "",
                    commentList.comments[i].text,
                    new Uri(commentList.comments[i].Uri),
                    commentList.comments[i].ID.ToString(),
                    DateTime.Parse(commentList.comments[i].Created.At));
                    items.Add(item);
                }

            }
            feed.Items = items;
            return feed;


        }
        protected virtual void ReadXml(XmlReader reader, SyndicationFeed result)
        {
            if (result == null)
                throw new ArgumentNullException("result");
            else if (reader == null)
                throw new ArgumentNullException("reader");

            reader.ReadStartElement();              // Read in <RDF>
            reader.ReadStartElement("channel");     // Read in <channel>
            while (reader.IsStartElement())         // Process <channel> children
            {
                if (reader.IsStartElement("title"))
                    result.Title = new TextSyndicationContent(reader.ReadElementString());
                else if (reader.IsStartElement("link"))
                    result.Links.Add(new SyndicationLink(new Uri(reader.ReadElementString())));
                else if (reader.IsStartElement("description"))
                    result.Description = new TextSyndicationContent(reader.ReadElementString());
                else
                    reader.Skip();
            }
            reader.ReadEndElement();                // Read in </channel>

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement("item"))
                {
                    result.Items = this.ReadItems(reader, result);

                    break;
                }
                else
                    reader.Skip();
            }
        }
Example #27
0
        private static FeedData GetFeed(SyndicationFeed feed, string contentType, WriteTo writeTo)
        {
            var feedData = new FeedData { ContentType = contentType };
            if (feed.Items.Any())
            {
                SyndicationItem item = (from syndicationItem in feed.Items
                                        orderby syndicationItem.PublishDate descending
                                        select syndicationItem).First();

                feedData.LastModifiedDate = item.PublishDate.DateTime;
            }
            else
            {
                feedData.LastModifiedDate = DateTime.MinValue;
            }

            var xmlWriterSettings = new XmlWriterSettings { Encoding = new UTF8Encoding(false) };

            var memoryStream = new MemoryStream();

            using (XmlWriter writer = XmlWriter.Create(memoryStream, xmlWriterSettings))
            {
                writeTo(writer);
            }

            memoryStream.Position = 0;
            var sr = new StreamReader(memoryStream);
            feedData.Content = sr.ReadToEnd();
            feedData.ETag = feedData.Content.GetHashCode().ToString();
            //}
            return feedData;
        }
Example #28
0
        static void Main(string[] args)
        {
            MemoryStream stream = new MemoryStream();

            //Simple feed with sample data
            SyndicationFeed feed = new SyndicationFeed("Custom JSON feed", "A Syndication extensibility sample", null);
            feed.LastUpdatedTime = DateTime.Now;
            feed.Items = from s in new string[] { "hello", "world" }
                         select new SyndicationItem()
                         {
                             Summary = SyndicationContent.CreatePlaintextContent(s)
                         };

            //Write the feed out to a MemoryStream as JSON
            DataContractJsonSerializer writeSerializer = new DataContractJsonSerializer(typeof(JsonFeedFormatter));
            writeSerializer.WriteObject(stream, new JsonFeedFormatter(feed));
            
            stream.Position = 0;

            //Read in the feed using the DataContractJsonSerializer
            DataContractJsonSerializer readSerializer = new DataContractJsonSerializer(typeof(JsonFeedFormatter));
            JsonFeedFormatter formatter = readSerializer.ReadObject(stream) as JsonFeedFormatter;
            SyndicationFeed feedRead = formatter.Feed;


            //Dump the JSON stream to the console
            string output = Encoding.UTF8.GetString(stream.GetBuffer());

            Console.WriteLine(output);
            Console.ReadLine();
        }
        private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                int itemsCount = 7;
                xmlReader = XmlReader.Create(new StringReader(e.Result));
                feed = SyndicationFeed.Load(xmlReader);

                List<RSSItem> itemsList = new List<RSSItem>();

                if (feed.Items.Count() < 7)
                {
                    itemsCount = feed.Items.Count();
                }

                for (int i = 0; i <= itemsCount; i++)
                {
                    RSSItem rssitem = new RSSItem();
                    rssitem.RSSTitle = feed.Items.ToList()[i].Title.Text;
                    rssitem.RSSLink = feed.Items.ToList()[i].Links[0].Uri;
                    itemsList.Add(rssitem);
                }
                RSS.ItemsSource = itemsList;
            }
        }
Example #30
0
        public Atom10FeedFormatter GetFeed(int id)
        {
            SyndicationFeed feed = new SyndicationFeed("Atom Feed", "This is a test feed", new Uri("http://SomeURI"), "FeedOneID", new DateTimeOffset(DateTime.Now));
            feed.Authors.Add(new SyndicationPerson("[email protected]"));
            feed.Categories.Add(new SyndicationCategory("How To Sample Code"));
            feed.Description = new TextSyndicationContent("This is a sample that illistrates how to expose a feed using ATOM with WCF");

            SyndicationItem item1 = new SyndicationItem(
                "Item One",
                "This is the content for item one",
                new Uri("http://localhost/Content/One"),
                "ItemOneID",
                DateTime.Now);

            SyndicationItem item2 = new SyndicationItem(
                "Item Two",
                "This is the content for item two",
                new Uri("http://localhost/Content/Two"),
                "ItemTwoID",
                DateTime.Now);

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

            items.Add(item1);
            items.Add(item2);

            feed.Items = items;
            return new Atom10FeedFormatter(feed);
        }