public bool Filter(SyndicationItem item)
 {
     return(item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
            item.Categories.Where(i => i.Name.Equals("Xamarin", StringComparison.OrdinalIgnoreCase)).Any());
 }
Beispiel #2
0
 /// <summary>
 /// Add the Atom entry to the collection. Return its id and the actual entry that was added to the collection.
 /// If the item could not be added return null.
 /// </summary>
 /// <param name="collection">collection name</param>
 /// <param name="entry">entry to be added</param>
 /// <param name="location">URI for the added entry</param>
 /// <returns></returns>
 protected abstract SyndicationItem AddEntry(string collection, SyndicationItem entry, out Uri location);
Beispiel #3
0
        public ActionResult GetRssEditorSuggestion()
        {
            StringBuilder str      = new StringBuilder();
            string        xmlFinal = string.Empty;

            var lstNoticias = SiteMapSrv.GetSiteMapSuggest().ToList();

            var lastDate = lstNoticias.First().DataPublicacao;

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

            var feed = new SyndicationFeed("Massa News - Todas as Noticias", "MassaNews - A notícia em movimento!", new Uri($"{Constants.UrlWeb}/{"noticias/plantao"}"));

            XNamespace dc = "http://purl.org/dc/elements/1.1/";

            feed.AttributeExtensions.Add(
                new XmlQualifiedName("dc", XNamespace.Xmlns.ToString()),
                "http://purl.org/dc/elements/1.1/");

            feed.ElementExtensions.Add(new XElement("image",
                                                    new XElement("url", null, $"{Constants.UrlCdn}/static/images/logos/massa-news-250x40.png"),
                                                    new XElement("title", null, "MassaNews - A notícia em movimento!"),
                                                    new XElement("link", null, $"{Constants.UrlWeb}/{"noticias/plantao"}")).CreateReader());

            var feedItems = new List <SyndicationItem>();

            //Cria os itens
            foreach (var noticia in lstNoticias)
            {
                var feedItem = new SyndicationItem
                {
                    Title = new TextSyndicationContent(noticia.Titulo),
                };

                foreach (var item in noticia.Creators)
                {
                    if (item == noticia.Creators.Last())
                    {
                        str.Append(item.Nome);
                    }
                    else
                    {
                        str.Append(item.Nome).Append(", ");
                    }
                }

                feedItem.ElementExtensions.Add(new XElement("link",
                                                            $"{Constants.UrlWeb}/{Url.Encode(noticia.EditorialUrl)}/{Url.Encode(noticia.CategoriaUrl)}/{Url.Encode(noticia.Url)}.html"));

                feedItem.ElementExtensions.Add(new XElement("description",
                                                            $"{(noticia.Description.Length > 220 ? Text.RemoveHtmlTags(noticia.Description.Substring(0, 220) + "... Leia mais no Massa News!") : Text.RemoveHtmlTags(noticia.Description) + " Leia no Massa News!")}"));

                feedItem.ElementExtensions.Add(new XElement(dc + "creator", str.ToString()));

                feedItems.Add(feedItem);
                str.Clear();
            }

            feed.Items = feedItems;
            MemoryStream output = new MemoryStream();
            //transforma para RSS
            SyndicationFeedFormatter rssFormatter = new Rss20FeedFormatter(feed);

            var xmlDoc = new XmlDocument();

            using (var xw = xmlDoc.CreateNavigator().AppendChild())
            {
                rssFormatter.WriteTo(xw);
            }
            //Adiciona a referência do namespace no cabeçalho do RSS
            xmlDoc.DocumentElement.SetAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");

            using (XmlWriter writer = XmlWriter.Create(output, new XmlWriterSettings {
                Indent = true
            }))
            {
                xmlDoc.WriteTo(writer);
            }

            xmlFinal = Encoding.UTF8.GetString(output.ToArray());

            var toReplace = $"channel xmlns:dc=\"http://purl.org/dc/elements/1.1/\"";

            xmlFinal = Regex.Replace(xmlFinal, toReplace, "channel");

            return(Content(xmlFinal.ToString(), "text/xml"));
        }
 public bool Filter(SyndicationItem item)
 {
     return(item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
            item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("xamarin")));
 }
Beispiel #5
0
        /// <summary>
        /// Wraparound processing.
        /// Here is the algorithm for selecting a feed item from a non-changing source, such as a
        /// defunct podcast or a directory of MP3 files.
        /// When processing a defunct source, generate a feed with only one item. You'll get a new item next period.
        /// </summary>
        /// <param name="sf">The sydication feed from which to select an item</param>
        /// <returns>A list with one item. That is the item to be saved into the RSS feed.</returns>
        public List <SyndicationItem> WrapAroundItems(SyndicationFeed sf)
        {
            DateTimeOffset forcedLastTimestamp = new DateTimeOffset(new DateTime(2016, 12, 31, 0, 0, 0), new TimeSpan(0));

            // Set the wraparound period according to the number of items in the source feed.
            double wrapDays = 7D; // skip to the next item every seventh day

            if (sf.Items.Count() > 700)
            {
                wrapDays = 1D; // skip to the next item every day
            }
            else if (sf.Items.Count() > 600)
            {
                wrapDays = 2D; // etc.
            }
            else if (sf.Items.Count() > 500)
            {
                wrapDays = 3D;
            }
            else if (sf.Items.Count() > 400)
            {
                wrapDays = 4D;
            }
            else if (sf.Items.Count() > 300)
            {
                wrapDays = 5D;
            }
            else if (sf.Items.Count() > 200)
            {
                wrapDays = 6D;
            }
            else
            {
                wrapDays = 7D;
            }

            try
            {
                if (sf.Items.Any())
                {
                    // There is at least one item, default to returning the last one (the latest one).
                    int selectIndex = sf.Items.Count() - 1;
                    // Get the date of the latest item
                    DateTimeOffset lastItemByModDt = (from feedItem in sf.Items
                                                      select feedItem.LastUpdatedTime).Max();

                    // Determine if an item has recenly been added to the feed
                    if (((DateTime.Now - lastItemByModDt.LocalDateTime).Days >= 2) &&
                        ((DateTime.Now - lastItemByModDt.LocalDateTime).Days <= 30) &&
                        (sf.Items.ElementAt(sf.Items.Count() - 1).LastUpdatedTime == lastItemByModDt))
                    {
                        // The most recent item is between 2 and 30 days old and the LastUpdatedTime of the last item in the list is the latest LastUpdatedTime.
                        // The source published a new item. Use this instead of the wraparound algorithm.
                        selectIndex = sf.Items.Count() - 1;
                    }
                    else
                    {
                        // Most MP3 files in most feeds will have a reasonable LastUpdatedTime. The clause above verifies that by considering only files at
                        // least two days old. But sometimes, LastUpdatedTime is junk, and may appear as the current date-time. So, aside from new items
                        // located above, never assume LastUpdatedTime is valid.  Assume the list of items is in ascending date-time order.
                        // Force a timestamp because if all the items have the same LastUpdatedTime, the same item will be selected every time.
                        // Start at 12/31/2016 (forcedLastTimestamp from above).
                        for (int iii = sf.Items.Count() - 1; iii >= 0; iii--)
                        {
                            // Set the current item's LastUpdatedTime to the current value of forcedLastTimestamp
                            sf.Items.ElementAt(iii).LastUpdatedTime = forcedLastTimestamp;
                            // Move backwards in time some number of days
                            forcedLastTimestamp = (forcedLastTimestamp - new TimeSpan(Convert.ToInt32(wrapDays), 0, 0, 0));
                        }

                        // Now the wraparound algorithm:
                        // Get the date of the earliest item. The point of forcing the timestamps is that for a defunct feed, the number
                        // of items will always be the same and firstItemByModDt will always be the same as long as wrapDays isn't changed
                        // and the initial value of forcedLastTimestamp isn't changed. As UtcNow progresses, selectIndex will progress.
                        DateTimeOffset firstItemByModDt = (from feedItem in sf.Items
                                                           select feedItem.LastUpdatedTime).Min();
                        // Determine the index of the item that should be chosen based on a wraparound time period.
                        // Start with the number of periods of wrapDays days, from the oldest item to today.
                        int periodsSinceFirst = Convert.ToInt32((DateTime.UtcNow - firstItemByModDt).TotalDays / wrapDays);
                        // Let's say the first item was Jan 1 2000, and today is Mar 1 2000.
                        // And let's say there are five items in the feed, indices 0-4.
                        // The number of days is 31 + 29 + 1 = 61, and periodsSinceFirst = 8 (since wrapDays is 7 for a feed with 5 items).
                        // selectIndex = 8 % 5 = 3, i.e., the item we want to keep in the generated feed is items[3], the 4th item.
                        // 100 items is 1.9 years worth of weekly items. 401 items is 4.4 years worth of 4-day items.
                        // You'll never cycle through thousands of items unless you're podcatching multiple times per day.
                        selectIndex = periodsSinceFirst % sf.Items.Count();
                    }

                    SyndicationItem siKeep = sf.Items.ElementAt(selectIndex);
                    // Pretend it was just published today
                    siKeep.LastUpdatedTime = new DateTimeOffset(DateTime.UtcNow, new TimeSpan(0));
                    siKeep.PublishDate     = new DateTimeOffset(DateTime.UtcNow, new TimeSpan(0));
                    // When processing a defunct source, generate a feed with only one item. You'll get a new item next period.
                    return(new List <SyndicationItem>()
                    {
                        siKeep
                    });
                }
            }
            catch
            {
                // Return null. The caller will presumably continue as if defunct feed processing did not occur.
            }
            return(null);
        }
Beispiel #6
0
 public static int Rank(this SyndicationItem item)
 {
     return(item.ElementExtensions
            .ReadElementExtensions <int>("rank", "http://purl.org/atompub/rank/1.0")
            .FirstOrDefault());
 }
Beispiel #7
0
 private Uri GetEpisodeUri(SyndicationItem item)
 {
     return(item.Links.SingleOrDefault(s => s.RelationshipType == "alternate").Uri);
 }
        public FeatureResult ImportItem(SyndicationItem item)
        {
            if (item != null) {

                List<XmlElement> elements = new List<XmlElement>();
                foreach (var element in item.ElementExtensions) {
                    elements.Add(element.GetObject<XmlElement>());
                }

                XmlElement geometry = ImportUtils.FindGmlGeometry(elements.ToArray());

                FeatureResult feature = new FeatureResult(Terradue.GeoJson.Geometry.GeometryFactory.GmlToFeature(geometry));

                NameValueCollection namespaces = null;
                XmlNamespaceManager xnsm = null;
                string prefix = "";

                if (options.KeepNamespaces) {

                    // Initialize namespaces
                    namespaces = new NameValueCollection();
                    namespaces.Set("", "http://geojson.org/ns#");
                    namespaces.Set("atom", "http://www.w3.org/2005/Atom");
                    XmlReader reader = item.ElementExtensions.GetReaderAtElementExtensions();
                    xnsm = new XmlNamespaceManager(reader.NameTable);
                    foreach (var names in xnsm.GetNamespacesInScope(XmlNamespaceScope.All)) {
                        namespaces.Set(names.Key, names.Value);
                    }
                    feature.Properties.Add("@namespaces", namespaces);
                    prefix = "atom:";
                }

                // Import Item
                if ((item.Authors != null) && (item.Authors.Count > 0)) {
                    object[] authors = new object[item.Authors.Count];
                    feature.Properties.Add(prefix + "authors", authors);
                    for (int i = 0; i < item.Authors.Count; i++) {
                        Dictionary<string,object> author = new Dictionary<string, object>();
                        author.Add(prefix + "name", item.Authors[i].Name);
                        author.Add(prefix + "email", item.Authors[i].Email);
                        author.Add(prefix + "uri", item.Authors[i].Uri);
                        author = author.Union(util.ImportAttributeExtensions(item.Authors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        author = author.Union(util.ImportElementExtensions(item.Authors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        authors[i] = author;
                    }
                }
                if (item.BaseUri != null) {
                    feature.Properties.Add(prefix + "uri", item.BaseUri.ToString());
                }
                if ((item.Categories != null) && (item.Categories.Count > 0)) {
                    object[] categories = new object[item.Categories.Count];
                    feature.Properties.Add(prefix + "categories", categories);
                    for (int i = 0; i < item.Categories.Count; i++) {
                        Dictionary<string,object> category = new Dictionary<string, object>();
                        category.Add(prefix + "name", item.Categories[i].Name);
                        category.Add(prefix + "label", item.Categories[i].Label);
                        category.Add(prefix + "scheme", item.Categories[i].Scheme);
                        category = category.Union(util.ImportAttributeExtensions(item.Categories[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        category = category.Union(util.ImportElementExtensions(item.Categories[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        categories[i] = category;
                    }
                }
                if ((item.Contributors != null) && (item.Contributors.Count > 0)) {
                    object[] contributors = new object[item.Contributors.Count];
                    feature.Properties.Add(prefix + "categories", contributors);
                    for (int i = 0; i < item.Contributors.Count; i++) {
                        Dictionary<string,object> contributor = new Dictionary<string, object>();
                        contributor.Add(prefix + "name", item.Contributors[i].Name);
                        contributor.Add(prefix + "email", item.Contributors[i].Email);
                        contributor.Add(prefix + "uri", item.Contributors[i].Uri);
                        contributor = contributor.Union(util.ImportAttributeExtensions(item.Contributors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        contributor = contributor.Union(util.ImportElementExtensions(item.Contributors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        contributors[i] = contributor;
                    }
                }
                if (item.Copyright != null) {
                    feature.Properties.Add(prefix + "rights", item.Copyright.Text);
                }
                if (item.Summary != null) {
                    feature.Properties.Add(prefix + "summary", item.Summary.Text);
                }
                if (item.Content != null) {
                    feature.Properties.Add(prefix + "content", item.Summary.Text);
                }
                feature.Id = item.Id;
                if (item.LastUpdatedTime != null)
                    feature.Properties.Add(prefix + "published", item.LastUpdatedTime);
                if ((item.Links != null) && (item.Links.Count > 0)) {
                    feature.Links = item.Links;
                }
                if (item.Title != null)
                    feature.Properties.Add(prefix + "title", item.Title);

                return feature;
            }

            return null;
        }
Beispiel #9
0
 private string[] GetCategories(SyndicationItem item)
 {
     return(item.Categories.Select(c => c.Name).ToArray());
 }
Beispiel #10
0
        private TimeSpan GetDuration(SyndicationItem item)
        {
            var duration = item.ElementExtensions.ReadElementExtensions <XElement>("duration", ITunesNamespace).Single().Value;

            return(TimeSpan.FromSeconds(Int32.Parse(duration)));
        }
Beispiel #11
0
 private string GetSummary(SyndicationItem item)
 {
     return(item.ElementExtensions.ReadElementExtensions <XElement>("summary", ITunesNamespace).Single().Value);
 }
 private SyndicationItemFormatter GetFormatter(SyndicationItem feedItem)
 {
     return (SyndicationItemFormatter)new Atom10ItemFormatter(feedItem);
 }
        /// <summary>
        /// Gets the collection of <see cref="SyndicationItem"/>'s that represent the atom entries.
        /// </summary>
        /// <returns>A collection of <see cref="SyndicationItem"/>'s.</returns>
        private List<SyndicationItem> GetItems()
        {
            List<SyndicationItem> items = new List<SyndicationItem>();

            for (int i = 1; i < 4; ++i)
            {
                SyndicationItem item = new SyndicationItem()
                {
                    // id (Required) - Identifies the entry using a universally unique and permanent URI. Two entries 
                    //                 in a feed can have the same value for id if they represent the same entry at 
                    //                 different points in time.
                    Id = FeedId + i,
                    // title (Required) - Contains a human readable title for the entry. This value should not be blank.
                    Title = SyndicationContent.CreatePlaintextContent("Item " + i),
                    // description (Recommended) - A summary of the entry.
                    Summary = SyndicationContent.CreatePlaintextContent("A summary of item " + i),
                    // updated (Optional) - Indicates the last time the entry was modified in a significant way. This 
                    //                      value need not change after a typo is fixed, only after a substantial 
                    //                      modification. Generally, different entries in a feed will have different 
                    //                      updated timestamps.
                    LastUpdatedTime = DateTimeOffset.Now,
                    // published (Optional) - Contains the time of the initial creation or first availability of the entry.
                    PublishDate = DateTimeOffset.Now,
                    // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the entry.
                    Copyright = new TextSyndicationContent(
                        string.Format("© {0} - {1}", DateTime.Now.Year, Application.Name)),
                };

                // link (Recommended) - Identifies a related Web page. An entry must contain an alternate link if there 
                //                      is no content element.
                item.Links.Add(SyndicationLink.CreateAlternateLink(
                    new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)),
                    ContentType.Html));
                // AND/OR
                // Text content  (Optional) - Contains or links to the complete content of the entry. Content must be 
                //                            provided if there is no alternate link.
                // item.Content = SyndicationContent.CreatePlaintextContent("The actual plain text content of the entry");
                // HTML content (Optional) - Content can be plain text or HTML. Here is a HTML example.
                // item.Content = SyndicationContent.CreateHtmlContent("The actual HTML content of the entry");

                // author (Optional) - Names one author of the entry. An entry may have multiple authors. An entry must 
                //                     contain at least one author element unless there is an author element in the 
                //                     enclosing feed, or there is an author element in the enclosed source element.
                item.Authors.Add(this.GetPerson());

                // contributor (Optional) - Names one contributor to the entry. An entry may have multiple contributor elements.
                item.Contributors.Add(this.GetPerson());

                // category (Optional) - Specifies a category that the entry belongs to. A entry may have multiple 
                //                       category elements.
                item.Categories.Add(new SyndicationCategory("CategoryName"));

                // link - Add additional links to related images, audio or video like so.
                item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(
                    new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png")),
                    ContentType.Png,
                    0));

                // media:thumbnail - Add a Yahoo Media thumbnail for the entry. See http://www.rssboard.org/media-rss 
                //                   for more information.
                item.SetThumbnail(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"), 48, 48);

                items.Add(item);
            }

            return items;
        }
Beispiel #14
0
 protected static void ConfigureAtomEntry(string collection, SyndicationItem entry, string id, out Uri location)
 {
     location = GetEntryUri(collection, id);
     entry.Links.Add(CreateEditLink(collection, id));
 }
Beispiel #15
0
 private Uri GetVideoUri(SyndicationItem item)
 {
     return(item.Links.SingleOrDefault(s => s.MediaType == "video/mp4").Uri);
 }
Beispiel #16
0
        /// <summary>
        /// Gets the collection of <see cref="SyndicationItem"/>'s that represent the atom entries.
        /// </summary>
        /// <returns>A collection of <see cref="SyndicationItem"/>'s.</returns>
        private List<SyndicationItem> GetItems()
        {
            List<SyndicationItem> items = new List<SyndicationItem>();

            for (int i = 1; i < 4; ++i)
            {
                SyndicationItem item = new SyndicationItem()
                {
                    // id (Required) - Identifies the entry using a universally unique and permanent URI. Two entries
                    //                 in a feed can have the same value for id if they represent the same entry at
                    //                 different points in time.
                    Id = FeedId + i,
                    // title (Required) - Contains a human readable title for the entry. This value should not be blank.
                    Title = SyndicationContent.CreatePlaintextContent("Item " + i),
                    // description (Recommended) - A summary of the entry.
                    Summary = SyndicationContent.CreatePlaintextContent("A summary of item " + i),
                    // updated (Optional) - Indicates the last time the entry was modified in a significant way. This
                    //                      value need not change after a typo is fixed, only after a substantial
                    //                      modification. Generally, different entries in a feed will have different
                    //                      updated timestamps.
                    LastUpdatedTime = DateTimeOffset.Now,
                    // published (Optional) - Contains the time of the initial creation or first availability of the entry.
                    PublishDate = DateTimeOffset.Now,
                    // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the entry.
                    Copyright = new TextSyndicationContent(
                        string.Format("© {0} - {1}", DateTime.Now.Year, Application.Name)),
                };

                // link (Recommended) - Identifies a related Web page. An entry must contain an alternate link if there
                //                      is no content element.
                item.Links.Add(SyndicationLink.CreateAlternateLink(
                    new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)),
                    ContentType.Html));
                // AND/OR
                // Text content  (Optional) - Contains or links to the complete content of the entry. Content must be
                //                            provided if there is no alternate link.
                // item.Content = SyndicationContent.CreatePlaintextContent("The actual plain text content of the entry");
                // HTML content (Optional) - Content can be plain text or HTML. Here is a HTML example.
                // item.Content = SyndicationContent.CreateHtmlContent("The actual HTML content of the entry");

                // author (Optional) - Names one author of the entry. An entry may have multiple authors. An entry must
                //                     contain at least one author element unless there is an author element in the
                //                     enclosing feed, or there is an author element in the enclosed source element.
                item.Authors.Add(this.GetPerson());

                // contributor (Optional) - Names one contributor to the entry. An entry may have multiple contributor elements.
                item.Contributors.Add(this.GetPerson());

                // category (Optional) - Specifies a category that the entry belongs to. A entry may have multiple
                //                       category elements.
                item.Categories.Add(new SyndicationCategory("CategoryName"));

                // link - Add additional links to related images, audio or video like so.
                item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(
                    new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png")),
                    ContentType.Png,
                    0));

                // media:thumbnail - Add a Yahoo Media thumbnail for the entry. See http://www.rssboard.org/media-rss
                //                   for more information.
                item.SetThumbnail(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"), 48, 48);

                items.Add(item);
            }

            return items;
        }
Beispiel #17
0
        /// <summary>
        /// Creates the syndication items from issue list.
        /// </summary>
        /// <param name="issueList">The issue list.</param>
        /// <returns></returns>
        private IEnumerable <SyndicationItem> CreateSyndicationItemsFromIssueList(IEnumerable <Issue> issueList)
        {
            var feedItems = new List <SyndicationItem>();

            foreach (Issue issue in issueList.Take(maxItemsInFeed))
            {
                // Atom items MUST have an author, so if there are no authors for this content item then go to next item in loop
                //if (outputAtom && t.TitleAuthors.Count == 0)
                //    continue;
                var item = new SyndicationItem
                {
                    Title = SyndicationContent.CreatePlaintextContent(string.Format("{0} - {1}", issue.FullId, issue.Title))
                };

                item.Links.Add(
                    SyndicationLink.CreateAlternateLink(
                        new Uri(
                            GetFullyQualifiedUrl(string.Format("~/Issues/IssueDetail.aspx?id={0}", issue.Id)))));
                item.Summary = SyndicationContent.CreatePlaintextContent(issue.Description);
                item.Categories.Add(new SyndicationCategory(issue.CategoryName));
                item.PublishDate = issue.DateCreated;

                // Add a custom element.
                var doc         = new XmlDocument();
                var itemElement = doc.CreateElement("milestone");
                itemElement.InnerText = issue.MilestoneName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("project");
                itemElement.InnerText = issue.ProjectName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("issueType");
                itemElement.InnerText = issue.IssueTypeName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("priority");
                itemElement.InnerText = issue.PriorityName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("status");
                itemElement.InnerText = issue.StatusName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("resolution");
                itemElement.InnerText = issue.ResolutionName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("assignedTo");
                itemElement.InnerText = issue.AssignedDisplayName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("owner");
                itemElement.InnerText = issue.OwnerDisplayName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("dueDate");
                itemElement.InnerText = issue.DueDate.ToShortDateString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("progress");
                itemElement.InnerText = issue.Progress.ToString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("estimation");
                itemElement.InnerText = issue.Estimation.ToString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("lastUpdated");
                itemElement.InnerText = issue.LastUpdate.ToShortDateString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("lastUpdateBy");
                itemElement.InnerText = issue.LastUpdateDisplayName;
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("created");
                itemElement.InnerText = issue.DateCreated.ToShortDateString();
                item.ElementExtensions.Add(itemElement);

                itemElement           = doc.CreateElement("createdBy");
                itemElement.InnerText = issue.CreatorDisplayName;
                item.ElementExtensions.Add(itemElement);

                //foreach (TitleAuthor ta in t.TitleAuthors)
                //{
                //    SyndicationPerson authInfo = new SyndicationPerson();
                //    authInfo.Email = ta.Author.au_lname + "@example.com";
                //    authInfo.Name = ta.Author.au_fullname;
                //    item.Authors.Add(authInfo);

                //    // RSS feeds can only have one author, so quit loop after first author has been added
                //    if (outputRss)
                //        break;
                //}
                var profile  = new WebProfile().GetProfile(issue.CreatorUserName);
                var authInfo = new SyndicationPerson {
                    Name = profile.DisplayName
                };
                //authInfo.Email = Membership.GetUser(IssueCreatorUserId).Email;
                item.Authors.Add(authInfo);

                // Add the item to the feed
                feedItems.Add(item);
            }

            return(feedItems);
        }
        protected EpmContentSerializerBase(EpmTargetTree tree, bool isSyndication, object element, SyndicationItem target)
#endif
        {
            this.Root    = isSyndication ? tree.SyndicationRoot : tree.NonSyndicationRoot;
            this.Element = element;
            this.Target  = target;
            this.Success = false;
        }
Beispiel #19
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);
        }
Beispiel #20
0
        /// <summary>
        /// Create a SyndicationItem for an MP3
        /// </summary>
        /// <param name="mp3Addr">The full MP3 link</param>
        /// <param name="itemDescPrefix">From the config file</param>
        /// <param name="guidPrefix">From the config file</param>
        /// <param name="homeUrl">From the config file</param>
        /// <param name="pubDate">The number</param>
        /// <returns>The item or an exception with info on what went wrong when trying to get the file info or null if couldn't get the info</returns>
        public SyndicationItem ItemForMp3(string mp3Addr, string itemDescPrefix, string guidPrefix,
                                          string homeUrl, bool allowHttps)
        {
            // First make sure the link points to a real file
            long     mp3Size = 0L;
            DateTime mp3Mod  = DateTime.UtcNow;
            bool     exists  = false;

            try
            {
                exists = Mp3Info(mp3Addr, out mp3Size, out mp3Mod);
            }
            catch (WebException)
            {
                exists = false; // Might be info in this exception and its inner exception
                throw;
            }
            catch (Exception)
            {
                exists = false;
                throw;
            }
            if (!exists)
            {
                return(null); // Retried a couple times but could not get the file info
            }
            // The W3C RSS validator reports a failure when an enclosure address uses https. After the MP3 is proved to exist (just above),
            // convert https to http if necessary. As far as I can tell, the resulting http link always works.
            // ALSO, https links don't work with my internet radio.
            if (!allowHttps && mp3Addr.ToLower().StartsWith("https"))
            {
                mp3Addr = "http" + mp3Addr.Substring(5);
            }

            Uri    myUri       = new Uri(mp3Addr);
            string baseMp3Name = myUri.Segments[myUri.Segments.Length - 1];             // The MP3 name including the extension
            string mp3Ext      = System.IO.Path.GetExtension(myUri.LocalPath);          // The extension including the period

            baseMp3Name = baseMp3Name.Substring(0, baseMp3Name.Length - mp3Ext.Length); // The name without the extension

            SyndicationItem si = new SyndicationItem();

            si.Id = guidPrefix + baseMp3Name; // guid

            SyndicationLink sl0 =
                new SyndicationLink(new Uri(homeUrl), "alternate", itemDescPrefix + "-" + baseMp3Name, null, 0);
            SyndicationLink sl1 = null;

            sl1 =
                new SyndicationLink(new Uri(mp3Addr), "enclosure", itemDescPrefix + "-" + baseMp3Name, "audio/mpeg", mp3Size);

            si.Links.Add(sl0);
            si.Links.Add(sl1);

            si.Summary = new TextSyndicationContent(itemDescPrefix + "-" + baseMp3Name, TextSyndicationContentKind.Plaintext);
            si.Title   = new TextSyndicationContent(itemDescPrefix + "-" + baseMp3Name, TextSyndicationContentKind.Plaintext);

            si.PublishDate     = new DateTimeOffset(mp3Mod, new TimeSpan(0));
            si.LastUpdatedTime = new DateTimeOffset(mp3Mod, new TimeSpan(0));

            return(si);
        }
Beispiel #21
0
 public void LoadNonAtomRss()
 {
     SyndicationItem.Load(XmlReader.Create(new StringReader("<dummy />")));
 }
Beispiel #22
0
        public async Task <IActionResult> Rss(string type, int count = 3)
        {
            _logger.LogDebug("Rss method called");
            string host = Request.Scheme + "://" + Request.Host;
            var    blog = await DataService.CustomFields.GetBlogSettings();

            var posts = await DataService.BlogPosts.GetList(count);

            var items = new List <SyndicationItem>();

            host = $"{host}{Url.Content("~/")}";

            var feed = new SyndicationFeed(
                blog.Title,
                blog.Description,
                new Uri(host),
                host,
                posts.FirstOrDefault().Published
                );

            if (posts != null && posts.Count() > 0)
            {
                foreach (var post in posts)
                {
                    var atomEntry = await FeedService.GetEntry(post, host);

                    var item = new SyndicationItem(
                        atomEntry.Title,
                        atomEntry.Description.MdToHtml(),
                        new Uri(atomEntry.Id),
                        atomEntry.Id,
                        atomEntry.Published
                        );
                    item.PublishDate = post.Published;

                    item.ElementExtensions.Add("summary", "", $"{post.Description.MdToHtml()}");
                    item.ElementExtensions.Add("cover", "", $"{host}{post.Cover}");

                    if (atomEntry.Categories != null && atomEntry.Categories.Count() > 0)
                    {
                        foreach (var category in atomEntry.Categories)
                        {
                            item.Categories.Add(new SyndicationCategory(category.Name));
                        }
                    }
                    items.Add(item);
                }
            }
            feed.Items = items;

            var settings = new XmlWriterSettings
            {
                Encoding            = Encoding.UTF8,
                NewLineHandling     = NewLineHandling.Entitize,
                NewLineOnAttributes = true,
                Indent = true
            };

            using (var stream = new MemoryStream())
            {
                using (var xmlWriter = XmlWriter.Create(stream, settings))
                {
                    var rssFormatter = new Rss20FeedFormatter(feed, false);
                    rssFormatter.WriteTo(xmlWriter);
                    xmlWriter.Flush();
                }
                return(File(stream.ToArray(), "application/xml; charset=utf-8"));
            }
        }
Beispiel #23
0
 public void LoadFeed()
 {
     // feed is not allowed.
     SyndicationItem.Load(XmlReader.Create(new StringReader("<feed xmlns=\"http://www.w3.org/2005/Atom\"></feed>")));
 }
Beispiel #24
0
        public ActionResult GetMainRss()
        {
            var lstNoticias = Service.Models.Noticia.GetLastestNews(5, true);

            var lastDate = lstNoticias.First().DataPublicacao;

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

            var feed = new SyndicationFeed
            {
                Title           = new TextSyndicationContent("Massa News - Todas as Noticias"),
                Language        = "pt-BR",
                LastUpdatedTime = new DateTimeOffset(lastDate.Value),
                Copyright       = new TextSyndicationContent("© Todos os direitos reservados.")
            };

            feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri($"{Constants.UrlWeb}/{"noticias"}")));

            feed.ImageUrl = new Uri($"{Constants.UrlCdn}/static/images/avatar/avatar-massanews-144x144.jpg");

            var feedItems = new List <SyndicationItem>();

            foreach (var noticia in lstNoticias)
            {
                var permalink = new Uri($"{Constants.UrlWeb}/{noticia.EditorialUrl}/{noticia.CategoriaUrl}/{noticia.Url}.html");

                var feedItem = new SyndicationItem
                {
                    Title       = new TextSyndicationContent(noticia.Titulo),
                    Content     = new TextSyndicationContent(StripHtml(noticia.Conteudo) + "... Leia mais no <a href='" + permalink + "'>Massa News</a>!"),
                    PublishDate = noticia.DataPublicacao ?? DateTime.Now,
                };

                //Adiciona Imagem ao item
                if (!string.IsNullOrEmpty(noticia.ImgLg))
                {
                    feedItem.ElementExtensions.Add(new XElement("image",
                                                                $"{Constants.UrlDominioEstaticoUploads}/noticias/{noticia.ImgLg}"));
                }

                feedItem.Links.Add(SyndicationLink.CreateAlternateLink(permalink));

                feedItems.Add(feedItem);
            }

            feed.Items = feedItems;

            SyndicationFeedFormatter rssFormatter = new Rss20FeedFormatter(feed);

            MemoryStream output = new MemoryStream();

            XmlWriterSettings ws = new XmlWriterSettings
            {
                Indent   = true,
                Encoding = new UTF8Encoding(false)
            };

            XmlWriter w = XmlWriter.Create(output, ws);

            rssFormatter.WriteTo(w);
            w.Flush();

            return(Content(Encoding.UTF8.GetString(output.ToArray()), "text/xml"));
        }
Beispiel #25
0
 public void LoadEntry()
 {
     SyndicationItem.Load(XmlReader.Create(new StringReader("<entry xmlns=\"http://www.w3.org/2005/Atom\"></entry>")));
 }
Beispiel #26
0
 public OwsContextAtomEntry(SyndicationItem it) : base(it)
 {
 }
Beispiel #27
0
        public void AddPermalinkNull()
        {
            SyndicationItem item = new SyndicationItem();

            item.AddPermalink(null);
        }
Beispiel #28
0
 public bool Filter(SyndicationItem item)
 {
     // This filters out only the posts that have the "PowerShell" category
     return(item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")));
 }
Beispiel #29
0
        public static void AddSorted(this ObservableCollection <SyndicationItem> list, SyndicationItem item)
        {
            int i = 0;

            while (i < list.Count && list[i].Compare(item) > 0)
            {
                i++;
            }

            list.Insert(i, item);
        }
Beispiel #30
0
 /// <summary>
 /// Update the Atom entry specified by the id. If none exists, return null. Return the updated Atom entry. Return null if the entry does not exist.
 /// This method must be idempotent.
 /// </summary>
 /// <param name="collection">collection name</param>
 /// <param name="id">id of the entry</param>
 /// <param name="entry">Entry to put</param>
 /// <returns></returns>
 protected abstract SyndicationItem PutEntry(string collection, string id, SyndicationItem entry);
 public bool Filter(SyndicationItem item)
 {
     // This filters out only the posts that have the "PowerShell" category
     return(item.Title.Text.ToLowerInvariant().Contains("powershell"));
 }
Beispiel #32
0
 public bool Filter(SyndicationItem item)
 {
     return(item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")));
 }
Beispiel #33
0
        // GET: rss/{subverseName}
        public ActionResult Rss(string subverseName)
        {
            var submissions = CacheHandler.Instance.Register <List <Submission> >(CachingKey.RssFeed(subverseName), new Func <List <Submission> >(() => {
                var result = new List <Submission>();
                using (var _db = new voatEntities())
                {
                    _db.EnableCacheableOutput();

                    if (subverseName != null && subverseName != "all")
                    {
                        // return only frontpage submissions from a given subverse
                        var subverse = DataCache.Subverse.Retrieve(subverseName); // _db.Subverse.Find(subverseName);
                        if (subverse != null)
                        {
                            //HACK: Disable subverse
                            if (subverse.IsAdminDisabled.HasValue && subverse.IsAdminDisabled.Value)
                            {
                                //ViewBag.Subverse = subverse.Name;
                                //return SubverseDisabledErrorView();
                                return(result);
                            }

                            result = (from message in _db.Submissions
                                      where !message.IsDeleted && message.Subverse == subverse.Name
                                      select message)
                                     .OrderByDescending(s => s.Rank)
                                     .Take(25)
                                     .ToList();
                        }
                    }
                    else if (subverseName == "all")
                    {
                        // return submissions from all subs
                        result = (from message in _db.Submissions
                                  join subverse in _db.Subverses on message.Subverse equals subverse.Name
                                  where !message.IsDeleted && subverse.IsPrivate != true && subverse.IsAdminPrivate != true && message.Rank > 0.00009
                                  where !(from bu in _db.BannedUsers select bu.UserName).Contains(message.UserName)
                                  select message).OrderByDescending(s => s.Rank).ThenByDescending(s => s.CreationDate).Take(25).ToList();
                    }
                    else
                    {
                        // return site-wide frontpage submissions
                        result = (from message in _db.Submissions
                                  where !message.IsDeleted
                                  join defaultsubverse in _db.DefaultSubverses on message.Subverse equals defaultsubverse.Subverse
                                  select message)
                                 .OrderByDescending(s => s.Rank)
                                 .Take(25)
                                 .ToList();
                    }
                }
                return(result);
            }), TimeSpan.FromMinutes(30));

            var feed = new SyndicationFeed("Voat", "Have your say", new Uri("http://www.voat.co"))
            {
                Language = "en-US",
                ImageUrl =
                    new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority +
                            "/Graphics/voat-logo.png")
            };

            var feedItems = new List <SyndicationItem>();

            foreach (var submission in submissions)
            {
                var commentsUrl = new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/v/" + submission.Subverse + "/comments/" + submission.ID);
                var subverseUrl = new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/v/" + submission.Subverse);

                var authorName = submission.UserName;
                // submission type submission
                if (submission.IsAnonymized)
                {
                    authorName = submission.ID.ToString(CultureInfo.InvariantCulture);
                }

                if (submission.Type == 1)
                {
                    var item = new SyndicationItem(
                        submission.Title,
                        submission.Content + "</br>" + "Submitted by " + "<a href='u/" + authorName + "'>" + authorName + "</a> to <a href='" + subverseUrl + "'>" + submission.Subverse + "</a> | <a href='" + commentsUrl + "'>" + CommentCounter.CommentCount(submission.ID) + " comments",
                        commentsUrl,
                        submission.ID.ToString(CultureInfo.InvariantCulture),
                        submission.CreationDate);
                    feedItems.Add(item);
                }
                else
                {
                    // link type submission
                    var linkUrl = new Uri(submission.Url);

                    // add a thumbnail if submission has one
                    if (submission.Thumbnail != null)
                    {
                        string thumbnailUrl;

                        if (Settings.UseContentDeliveryNetwork)
                        {
                            thumbnailUrl = new Uri("http://cdn." + System.Web.HttpContext.Current.Request.Url.Authority + "/thumbs/" + submission.Thumbnail).ToString();
                        }
                        else
                        {
                            thumbnailUrl = new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/Thumbs/" + submission.Thumbnail).ToString();
                        }

                        var item = new SyndicationItem(
                            submission.Title,
                            "<a xmlns='http://www.w3.org/1999/xhtml' href='" + commentsUrl + "'><img title='" + submission.Title + "' alt='" + submission.Title + "' src='" + thumbnailUrl + "' /></a>" +
                            "</br>" +
                            "Submitted by " + "<a href='u/" + authorName + "'>" + authorName + "</a> to <a href='" + subverseUrl + "'>" + submission.Subverse + "</a> | <a href='" + commentsUrl + "'>" + CommentCounter.CommentCount(submission.ID) + " comments</a>" +
                            " | <a href='" + linkUrl + "'>link</a>",
                            commentsUrl,
                            submission.ID.ToString(CultureInfo.InvariantCulture),
                            submission.CreationDate);

                        feedItems.Add(item);
                    }
                    else
                    {
                        var item = new SyndicationItem(
                            submission.Title,
                            "Submitted by " + "<a href='u/" + authorName + "'>" + authorName + "</a> to <a href='" + subverseUrl + "'>" + submission.Subverse + "</a> | <a href='" + commentsUrl + "'>" + CommentCounter.CommentCount(submission.ID) + " comments",
                            commentsUrl,
                            submission.ID.ToString(CultureInfo.InvariantCulture),
                            submission.CreationDate);
                        feedItems.Add(item);
                    }
                }
            }

            feed.Items = feedItems;
            return(new FeedResult(new Rss20FeedFormatter(feed)));
        }
Beispiel #34
0
        /// <summary>
        /// Gets the collection of <see cref="SyndicationItem"/>'s that represent the atom entries.
        /// </summary>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> signifying if the request is cancelled.</param>
        /// <returns>A collection of <see cref="SyndicationItem"/>'s.</returns>
        private async Task<List<SyndicationItem>> GetItems(CancellationToken cancellationToken)
        {
            List<SyndicationItem> items = new List<SyndicationItem>();

            foreach (var article in _feedContext.GetArticlesToday())
            {
                SyndicationItem item = new SyndicationItem()
                {
                    // id (Required) - Identifies the entry using a universally unique and permanent URI. Two entries 
                    //                 in a feed can have the same value for id if they represent the same entry at 
                    //                 different points in time.
                    Id = string.Format("{0}/{1}", SiteUrl, article.Url),
                    // title (Required) - Contains a human readable title for the entry. This value should not be blank.
                    Title = SyndicationContent.CreatePlaintextContent(article.Title),
                    // description (Recommended) - A summary of the entry.
                    //Summary = SyndicationContent.CreatePlaintextContent(article.Summary),
                    // updated (Optional) - Indicates the last time the entry was modified in a significant way. This 
                    //                      value need not change after a typo is fixed, only after a substantial 
                    //                      modification. Generally, different entries in a feed will have different 
                    //                      updated timestamps.
                    LastUpdatedTime = article.DatePublish,
                    // published (Optional) - Contains the time of the initial creation or first availability of the entry.
                    PublishDate = article.DatePublish,
                    // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the entry.
                    Copyright = new TextSyndicationContent(
                        string.Format("© {0} - {1}", DateTime.Now.Year, "moemisto.com.ua")),
                    // link (Recommended) - Identifies a related Web page. An entry must contain an alternate link if there 
                    //                      is no content element.
                    Links = new Collection<SyndicationLink>
                    {
                        SyndicationLink.CreateAlternateLink(new Uri(string.Format("{0}/{1}", SiteUrl, article.Url)))
                    },  
                     
                    // AND/OR
                    // Text content  (Optional) - Contains or links to the complete content of the entry. Content must be 
                    //                            provided if there is no alternate link.
                    // item.Content = SyndicationContent.CreatePlaintextContent("The actual plain text content of the entry");
                    // HTML content (Optional) - Content can be plain text or HTML. Here is a HTML example.
                    Content = SyndicationContent.CreatePlaintextContent(article.Summary) , //SyndicationContent.CreateHtmlContent(article.Content)
                    
                    // author (Optional) - Names one author of the entry. An entry may have multiple authors. An entry must 
                    //                     contain at least one author element unless there is an author element in the 
                    //                     enclosing feed, or there is an author element in the enclosed source element.
                    //item.Authors.Add(GetPerson());

                    // contributor (Optional) - Names one contributor to the entry. An entry may have multiple contributor elements.
                    //item.Contributors.Add(GetPerson());

                    // category (Optional) - Specifies a category that the entry belongs to. A entry may have multiple 
                    //                       category elements.

                };

                item.Categories.Add(new SyndicationCategory(article.CategoryName));
                item.ElementExtensions.Add(
                    new XElement("enclosure",
                        new XAttribute("type", "image/jpeg"),
                        new XAttribute("url", string.Format("{0}/{1}", SiteUrl, article.PictureUrl))
                        ).CreateReader()
                );

                items.Add(item);
            }

            return items;
        }
Beispiel #35
0
        SyndicationItem GetAtomItem(AtompubViewModel vm, Post post)
        {
            string authorEmail = post.Email;
              string authorName = post.Author;
              if (string.IsNullOrWhiteSpace(authorEmail) && string.IsNullOrWhiteSpace(authorName)) {
            authorEmail = vm.ContactEmail;
            authorName = vm.ContactName;
              }

              var entry = new SyndicationItem() {
            Content = new TextSyndicationContent(post.Content, TextSyndicationContentKind.Html),
            Id = GetPostLink(post.Id),
            LastUpdatedTime = post.CreationDate,
            Links = {
              new SyndicationLink(new Uri(GetAtomPostLink(post.Id)), "edit", null, null, 0),
              new SyndicationLink(new Uri(GetPostLink(post.Id)), "alternate", null, "text/html", 0),
            },
            PublishDate = post.CreationDate,
            Title = new TextSyndicationContent(post.Title),
            Authors = { new SyndicationPerson(authorEmail, authorName, null) },
              };

              // Split each item category with embedded commas
              if (post.Categories != null && post.Categories.Contains(',')) {
            foreach (var category in post.Categories.Split(',')) {
              entry.Categories.Add(new SyndicationCategory(category));
            }
              }

              return entry;
        }