Пример #1
0
        public void WriteElementExtensions_Person_Success(string version)
        {
            var person    = new SyndicationPerson();
            var formatter = new Formatter();

            CompareHelper.AssertEqualWriteOutput("", writer => formatter.WriteElementExtensionsEntryPoint(writer, person, version));

            person.ElementExtensions.Add(new ExtensionObject {
                Value = 10
            });
            person.ElementExtensions.Add(new ExtensionObject {
                Value = 11
            });
            CompareHelper.AssertEqualWriteOutput(
                @"<SyndicationItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
    <Value>10</Value>
</SyndicationItemFormatterTests.ExtensionObject>
<SyndicationItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
    <Value>11</Value>
</SyndicationItemFormatterTests.ExtensionObject>", writer => formatter.WriteElementExtensionsEntryPoint(writer, person, version));
        }
Пример #2
0
        public void Write()
        {
            DateTimeOffset offset = DateTimeOffset.UtcNow;

            string expectedBody = String.Format("<rss xmlns:a10=\"http://www.w3.org/2005/Atom\" version=\"2.0\"><channel><title>Test Feed</title><link>http://www.springframework.net/Feed</link><description>This is a test feed</description><copyright>Copyright 2010</copyright><managingEditor>[email protected]</managingEditor><lastBuildDate>{0}</lastBuildDate><a10:id>Atom10FeedHttpMessageConverterTests.Write</a10:id></channel></rss>",
                                                offset.ToString("ddd, dd MMM yyyy HH:mm:ss Z", CultureInfo.InvariantCulture));

            SyndicationFeed   body = new SyndicationFeed("Test Feed", "This is a test feed", new Uri("http://www.springframework.net/Feed"), "Atom10FeedHttpMessageConverterTests.Write", offset);
            SyndicationPerson sp   = new SyndicationPerson("*****@*****.**", "Bruno Baïa", "http://www.springframework.net/bbaia");

            body.Authors.Add(sp);
            body.Copyright = new TextSyndicationContent("Copyright 2010");

            MockHttpOutputMessage message = new MockHttpOutputMessage();

            converter.Write(body, null, message);

            Assert.AreEqual(expectedBody, message.GetBodyAsString(Encoding.UTF8), "Invalid result");
            Assert.AreEqual(new MediaType("application", "rss+xml"), message.Headers.ContentType, "Invalid content-type");
            //Assert.IsTrue(message.Headers.ContentLength > -1, "Invalid content-length");
        }
Пример #3
0
        public void Ctor_SyndicationPerson_Full()
        {
            var original = new SyndicationPerson("email", "name", "uri");

            original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value");
            original.ElementExtensions.Add(new ExtensionObject {
                Value = 10
            });

            var clone = new SyndicationPersonSubclass(original);

            Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions);
            Assert.Equal(1, clone.AttributeExtensions.Count);
            Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]);

            Assert.NotSame(clone.ElementExtensions, original.ElementExtensions);
            Assert.Equal(1, clone.ElementExtensions.Count);
            Assert.Equal(10, clone.ElementExtensions[0].GetObject <ExtensionObject>().Value);

            Assert.Equal("email", clone.Email);
            Assert.Equal("name", clone.Name);
            Assert.Equal("uri", clone.Uri);
        }
Пример #4
0
        private async Task addEntry(FeedSource source, HtmlNode nextNode)
        {
            HtmlNode urlNode = nextNode.QuerySelector(source.Entries.Url.Selector);

            if (urlNode == null)
            {
                throw new ApplicationException("Error: Failed to match entry url selector against an element.");
            }

            string url = source.Entries.Url.Attribute == string.Empty ?
                         urlNode.InnerText : urlNode.Attributes[source.Entries.Url.Attribute].DeEntitizeValue;

            Uri       entryUri = new Uri(new Uri(source.Feed.Url), new Uri(url));
            AtomEntry nextItem = new AtomEntry()
            {
                Id          = entryUri.ToString(),
                Title       = ReferenceSubstitutor.Replace(source.Entries.Title, nextNode),
                Description = ReferenceSubstitutor.Replace(source.Entries.Content, nextNode),
                ContentType = "html"
            };

            nextItem.AddLink(new SyndicationLink(entryUri, AtomLinkTypes.Alternate));

            if (source.Entries.Published != null)
            {
                nextItem.Published = DateTime.Parse(
                    nextNode.QuerySelectorAttributeOrText(
                        source.Entries.Published
                        )
                    );
            }

            if (source.Entries.LastUpdated != null)
            {
                nextItem.LastUpdated = DateTime.Parse(
                    nextNode.QuerySelectorAttributeOrText(
                        source.Entries.LastUpdated
                        )
                    );
            }
            else if (source.Entries.Published != null)             // Use the publish date if available
            {
                nextItem.LastUpdated = nextItem.Published;
            }
            else             // It requires one, apparently
            {
                nextItem.LastUpdated = DateTimeOffset.Now;
            }


            if (source.Entries.AuthorName != null)
            {
                SyndicationPerson author = new SyndicationPerson(
                    nextNode.QuerySelectorAttributeOrText(source.Entries.AuthorName).Trim(),
                    ""
                    );
                if (source.Entries.AuthorUrl != null)
                {
                    author.Uri = nextNode.QuerySelectorAttributeOrText(source.Entries.AuthorUrl);
                }

                nextItem.AddContributor(author);
            }
            else
            {
                nextItem.AddContributor(new SyndicationPerson("Unknown", ""));
            }


            await feed.Write(nextItem);
        }
Пример #5
0
        private void UpdateSyndicationFeed()
        {
            //See if feed is already in the cache
            List <SyndicationItem> items = Cache["AudiosFeed"] as List <SyndicationItem>;

            if (items == null)
            {
                var container = client.GetContainerReference(companyName.ToLower());
                var blob      = container.GetBlockBlobReference("audios/" + "audio.rss");
                using (MemoryStream ms = new MemoryStream())
                {
                    blob.DownloadToStream(ms);
                    StreamReader reader = new StreamReader(ms);
                    if (reader != null)
                    {
                        reader.BaseStream.Position = 0;
                    }
                    SyndicationFeed audiosList = SyndicationFeed.Load(XmlReader.Create(ms));
                    items = audiosList.Items.ToList <SyndicationItem>();
                    //Custom Tags
                    string           prefix   = "itunes";
                    XmlQualifiedName nam      = new XmlQualifiedName(prefix, "http://www.w3.org/2000/xmlns/");
                    XNamespace       itunesNs = "http://www.itunes.com/dtds/podcast-1.0.dtd";
                    audiosList.AttributeExtensions.Add(nam, itunesNs.NamespaceName);
                    SyndicationItem item = new SyndicationItem();


                    //Create syndication Item
                    item.Title       = TextSyndicationContent.CreatePlaintextContent(name.Text);
                    item.PublishDate = DateTimeOffset.Now;
                    item.Links.Add(SyndicationLink.CreateAlternateLink(uri));
                    item.ElementExtensions.Add(new SyndicationElementExtension("author", itunesNs.NamespaceName, name.Text));
                    item.ElementExtensions.Add(new SyndicationElementExtension("explicit", itunesNs.NamespaceName, "no"));
                    item.ElementExtensions.Add(new SyndicationElementExtension("summary", itunesNs.NamespaceName, description.Text));
                    item.ElementExtensions.Add(new SyndicationElementExtension("subtitle", itunesNs.NamespaceName, subtitle.Text));
                    item.ElementExtensions.Add(
                        new XElement(itunesNs + "image", new XAttribute("href", uri2.ToString())));
                    item.ElementExtensions.Add(new SyndicationElementExtension("Size", null, upload_file.PostedFile.ContentLength / 1000000));

                    item.Summary = TextSyndicationContent.CreatePlaintextContent(description.Text);
                    item.Categories.Add(new SyndicationCategory(category.Text));
                    SyndicationLink enclosure = SyndicationLink.CreateMediaEnclosureLink(uri, "audio/mpeg", upload_file.PostedFile.ContentLength);
                    item.ElementExtensions.Add(new SyndicationElementExtension("subtitle", itunesNs.NamespaceName, subtitle.Text));
                    item.Links.Add(enclosure);

                    //create author Info
                    SyndicationPerson authInfo = new SyndicationPerson();
                    authInfo.Name = authorName.Text;
                    item.Authors.Add(authInfo);
                    items.Add(item);

                    //recreate Feed
                    audiosList.Items = items;
                    blob.Delete();

                    MemoryStream       ms1          = new MemoryStream();
                    XmlWriter          feedWriter   = XmlWriter.Create(ms1);
                    Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(audiosList);
                    rssFormatter.WriteTo(feedWriter);
                    feedWriter.Close();

                    blob.UploadFromByteArray(ms1.ToArray(), 0, ms1.ToArray().Length);
                    ms1.Close();
                }
                Cache.Insert("AudiosFeed",
                             items,
                             null,
                             DateTime.Now.AddHours(1.0),
                             TimeSpan.Zero);
            }
        }
Пример #6
0
        //TODO: Major refractor
        public ActionResult Feed(ContentModel model)
        {
            var blogPage = this._viewModelFactory.CreateModel(null, model);

            this._umbracoMapper.Map(model.Content, blogPage);
            var blogUrl = "https://" + Request.Url.Host + blogPage.Url + "";

            var syndicationItems = new List <SyndicationItem>();

            var author = new SyndicationPerson(Rasolo.Services.Constants.Project.Email, "Rasmus Olofsson", "https://rasolo.net");

            author.ElementExtensions.Add("title", string.Empty, "Web developer");


            author.ElementExtensions.Add("image", string.Empty, "https://rasolo.net/media/5a1pqhxs/rasolo.png");

            SyndicationFeed feed = new SyndicationFeed(blogPage.Title, blogPage?.MainBody?.ToString().StripHtml(), new System.Uri(Request.Url.AbsoluteUri))
            {
                Language = "en-us",
                Id       = blogUrl,
                Authors  = { author }
            };
            //var blogPostPages = blogPage.Children;
            var blogPostPages = new List <BlogPostPage.BlogPostPage>();

            this._umbracoMapper.MapCollection(blogPage.Children, blogPostPages);

            foreach (var blogPostPage in blogPostPages)
            {
                var blogPostPageUrl = "https://" + Request.Url.Host + blogPostPage.Url + "";

                var blogPostUri =
                    new Uri(blogPostPageUrl);
                var blogPostContent  = new TextSyndicationContent(HttpUtility.HtmlDecode(blogPostPage.MainBody?.ToString().StripHtml()));
                var blogPostFeedItem = new SyndicationItem(blogPostPage.Title,
                                                           blogPostContent.ToString(),
                                                           blogPostUri);
                blogPostFeedItem.ElementExtensions.Add("author", string.Empty, Rasolo.Services.Constants.Project.Email);
                blogPostFeedItem.PublishDate     = blogPostPage.CreateDate;
                blogPostFeedItem.LastUpdatedTime = blogPostPage.UpdateDate.ToUniversalTime();


                blogPostFeedItem.Content = blogPostContent;

                blogPostFeedItem.Categories.Add(new SyndicationCategory(blogPage.Name));
                syndicationItems.Add(blogPostFeedItem);
            }

            feed.LastUpdatedTime = blogPostPages.OrderByDescending(x => x.UpdateDate)
                                   .FirstOrDefault()
                                   .UpdateDate.ToUniversalTime();


            feed.Items = syndicationItems;
            SyndicationLink link = new SyndicationLink(
                new Uri(blogUrl + "feed"), "self", "type", "text/xml", 1000);

            feed.Links.Add(link);

            var result = new RssResult(feed);

            return(result);
        }
Пример #7
0
        public override AtomItem ToAtomItem(NameValueCollection parameters)
        {
            if (!IsSearchable(parameters))
            {
                return(null);
            }

            UserTep owner = (UserTep)UserTep.ForceFromId(context, this.OwnerId);

            //string identifier = null;
            string name        = (Entity.Name != null ? Entity.Name : Entity.Identifier);
            string description = null;
            Uri    id          = new Uri(context.BaseUrl + "/" + this.ActivityEntityType.Keyword + "/search?id=" + Entity.Identifier);

            switch (this.Privilege.Operation)
            {
            case EntityOperationType.Create:
                description = string.Format("created {0} '{1}'", this.ActivityEntityType.SingularCaption, name);
                break;

            case EntityOperationType.Change:
                description = string.Format("updated {0} '{1}'", this.ActivityEntityType.SingularCaption, name);
                break;

            case EntityOperationType.Delete:
                description = string.Format("deleted {0} '{1}'", this.ActivityEntityType.SingularCaption, name);
                break;

            case EntityOperationType.Share:
                description = string.Format("shared {0} '{1}'", this.ActivityEntityType.SingularCaption, name);
                break;

            default:
                break;
            }

            //AtomItem atomEntry = null;
            AtomItem result = new AtomItem();

            result.Id      = id.ToString();
            result.Title   = new TextSyndicationContent(base.Entity.Identifier);
            result.Content = new TextSyndicationContent(name);

            result.ElementExtensions.Add("identifier", "http://purl.org/dc/elements/1.1/", Guid.NewGuid());
            result.Summary         = new TextSyndicationContent(description);
            result.ReferenceData   = this;
            result.PublishDate     = this.CreationTime;
            result.LastUpdatedTime = this.CreationTime;
            var basepath = new UriBuilder(context.BaseUrl);

            basepath.Path = "user";
            string            usrUri  = basepath.Uri.AbsoluteUri + "/" + owner.Username;
            string            usrName = (!String.IsNullOrEmpty(owner.FirstName) && !String.IsNullOrEmpty(owner.LastName) ? owner.FirstName + " " + owner.LastName : owner.Username);
            SyndicationPerson author  = new SyndicationPerson(null, usrName, usrUri);
            var ownername             = string.IsNullOrEmpty(owner.FirstName) || string.IsNullOrEmpty(owner.LastName) ? owner.Username : owner.FirstName + " " + owner.LastName;

            author.ElementExtensions.Add(new SyndicationElementExtension("identifier", "http://purl.org/dc/elements/1.1/", ownername));
            author.ElementExtensions.Add(new SyndicationElementExtension("avatar", "http://purl.org/dc/elements/1.1/", owner.GetAvatar()));
            result.Authors.Add(author);
            result.Links.Add(new SyndicationLink(id, "self", name, "application/atom+xml", 0));
            Uri share = new Uri(context.BaseUrl + "/share?url=" + System.Web.HttpUtility.UrlEncode(id.AbsoluteUri) + (!string.IsNullOrEmpty(AppId) ? "&id=" + AppId : ""));

            result.Links.Add(new SyndicationLink(share, "related", "share", "application/atom+xml", 0));

            return(result);
        }
Пример #8
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);
        }
Пример #9
0
 public static void WriteAttributeExtensionsEntryPoint(XmlWriter writer, SyndicationPerson person, string version)
 {
     WriteAttributeExtensions(writer, person, version);
 }
Пример #10
0
        public virtual SyndicationFeed LoadFeed()
        {
            SyndicationFeed feed = new SyndicationFeed("Припевы!", "Припевы! Комплектуются куплетами и аккордами.", new Uri(Utils.Registry.GetString("ServerURL")), null, DateTime.Now);

            XmlQualifiedName xqName = new XmlQualifiedName("encoding");

            feed.AttributeExtensions.Add(xqName, "windows-1251");

            feed.Language  = "ru";
            feed.Copyright = new TextSyndicationContent("Copyright (c) 1999-" + DateTime.Now.Year.ToString() + " Aleksey Grachev", TextSyndicationContentKind.Plaintext);

            SyndicationPerson sp = new SyndicationPerson("*****@*****.**", "Aleksey Grachev", "http://Aleksey/Grachev");

            feed.Authors.Add(sp);

            XmlDocument doc          = new XmlDocument();
            XmlElement  feedElement1 = doc.CreateElement("webMaster");

            feedElement1.InnerText = "*****@*****.**";
            feed.ElementExtensions.Add(feedElement1);
            XmlElement feedElement2 = doc.CreateElement("ttl");

            feedElement2.InnerText = "1440";
            feed.ElementExtensions.Add(feedElement2);

            SyndicationCategory category = new SyndicationCategory("Music");

            feed.Categories.Add(category);

            feed.ImageUrl = new Uri(Pripev.Utils.Registry.GetString("ServerURL") + "/Images/Banners/PripevRSS.gif");

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

            DataTable dt = DAL.DB.ExecuteDataTable("exec GetFeed @FeedType='Artists',@StartDate=" + Utils.Convert.ToSQLString(_modifiedSince));

            foreach (DataRow dr in dt.Rows)
            {
                SyndicationItem item = new SyndicationItem("Исполнитель: " + dr["NAME"].ToString(),
                                                           "Новый исполнитель: " + dr["NAME"].ToString(),
                                                           new Uri(Utils.Registry.GetString("ServerURL") + "/Artist.aspx?Id=" + dr["ARTIST_ID"].ToString()));
                items.Add(item);
            }

            dt = DAL.DB.ExecuteDataTable("exec GetFeed @FeedType='Albums',@StartDate=" + Utils.Convert.ToSQLString(_modifiedSince));
            foreach (DataRow dr in dt.Rows)
            {
                SyndicationItem item = new SyndicationItem("Альбом: " + dr["AlbumName"].ToString(),
                                                           "Новый альбом: " + dr["AlbumName"].ToString() + "<br>" + "Исполнитель: " + dr["ArtistName"].ToString(),
                                                           new Uri(Utils.Registry.GetString("ServerURL") + "/Album.aspx?Id=" + dr["ALBUM_ID"].ToString()));
                items.Add(item);
            }

            dt = DAL.DB.ExecuteDataTable("exec GetFeed @FeedType='Texts',@StartDate=" + Utils.Convert.ToSQLString(_modifiedSince));
            foreach (DataRow dr in dt.Rows)
            {
                SyndicationItem item = new SyndicationItem("Текст: " + dr["SongName"].ToString(),
                                                           "Добавлена композиция: " + dr["SongName"].ToString() + "<br>" +
                                                           "Табы/Аккорды: " + (dr["Chords"].ToString() == "Y" ? "Есть" : "Нет") + "<br>" +
                                                           "Исполнитель: " + dr["ArtistName"].ToString() + "<br>" +
                                                           "Альбом: " + dr["AlbumName"].ToString(),
                                                           new Uri(Utils.Registry.GetString("ServerURL") + "/Text.aspx?Id=" + dr["TextId"].ToString() + "&SongId=" + dr["SongId"].ToString()));
                items.Add(item);
            }

            dt = DAL.DB.ExecuteDataTable("exec GetFeed @FeedType='Sounds',@StartDate=" + Utils.Convert.ToSQLString(_modifiedSince));
            foreach (DataRow dr in dt.Rows)
            {
                SyndicationItem item = new SyndicationItem("Звук: " + dr["SongName"].ToString(),
                                                           "Добавлена композиция: " + dr["SongName"].ToString() + "<br>" +
                                                           "Тип файла: " + dr["SoundType"].ToString() + "<br>" +
                                                           "Исполнитель: " + dr["ArtistName"].ToString() + "<br>" +
                                                           "Альбом: " + dr["AlbumName"].ToString(),
                                                           new Uri(Utils.Registry.GetString("ServerURL") + "/Album.aspx?Id=" + dr["AlbumId"].ToString()));
                items.Add(item);
            }

            feed.Items = items;

            return(feed);
        }
Пример #11
0
        public static async Task <SyndicationFeed> BuildSyndication(this IBlogService service, string baseAddress)
        {
            ClientUriGenerator generator = new ClientUriGenerator
            {
                BaseAddress = baseAddress
            };
            BlogOptions blogOptions = await service.GetOptions();

            SyndicationFeed   feed   = new SyndicationFeed(blogOptions.Name, blogOptions.Description, new Uri(baseAddress));
            SyndicationPerson author = new SyndicationPerson("", blogOptions.Onwer, baseAddress);

            feed.Authors.Add(author);
            Dictionary <string, SyndicationCategory> categoryMap = new Dictionary <string, SyndicationCategory>();

            {
                var cates = await service.PostService.GetCategories();

                foreach (var p in cates.AsCategoryList())
                {
                    var cate = new SyndicationCategory(p.ToString());
                    categoryMap.Add(p.ToString(), cate);
                    feed.Categories.Add(cate);
                }
            }
            {
                var posts = service.PostService.GetAllItems().IgnoreNull();
                List <SyndicationItem> items = new List <SyndicationItem>();
                await foreach (var p in posts)
                {
                    if (p is null)
                    {
                        continue;
                    }
                    var s = new SyndicationItem(p.Title,
                                                SyndicationContent.CreateHtmlContent(Markdown.ToHtml(p.Content.Raw, Pipeline)),
                                                new Uri(generator.Post(p)), p.Id, p.ModificationTime);
                    s.Authors.Add(author);

                    string summary;
                    if (await service.PostService.Protector.IsProtected(p.Content))
                    {
                        summary = "Protected Post";
                    }
                    else
                    {
                        summary = Markdown.ToPlainText(p.Content.Raw, Pipeline);
                    }
                    s.Summary = SyndicationContent.CreatePlaintextContent(summary.Length <= 100 ? summary : summary.Substring(0, 100));
                    s.Categories.Add(new SyndicationCategory(p.Category.ToString()));
                    if (categoryMap.TryGetValue(p.Category.ToString(), out var cate))
                    {
                        s.Categories.Add(cate);
                    }
                    s.PublishDate = p.CreationTime;
                    items.Add(s);
                }
                feed.Items = items.AsEnumerable();
            }

            return(feed);
        }
Пример #12
0
        public JsonObject process(String feedUrl, String feedXml,
                                  bool getSummaries, int numEntries)
        {
            JsonObject      json   = new JsonObject();
            XmlReader       reader = XmlReader.Create(feedUrl);
            SyndicationFeed feed   = SyndicationFeed.Load(reader);

            if (feed == null)
            {
                throw new GadgetException(GadgetException.Code.FAILED_TO_RETRIEVE_CONTENT,
                                          "Unable to retrieve feed xml.");
            }
            json.Put("Title", feed.Title);
            json.Put("URL", feedUrl);
            json.Put("Description", feed.Description);
            json.Put("Link", feed.Links);

            var    authors    = feed.Authors;
            String jsonAuthor = null;

            if (authors.Count != 0)
            {
                SyndicationPerson author = authors[0];
                if (!String.IsNullOrEmpty(author.Name))
                {
                    jsonAuthor = author.Name;
                }
                else if (!String.IsNullOrEmpty(author.Email))
                {
                    jsonAuthor = author.Email;
                }
            }

            JsonArray entries = new JsonArray();

            json.Put("Entry", entries);

            int entryCnt = 0;

            foreach (var obj in feed.Items)
            {
                SyndicationItem e = obj;
                if (entryCnt >= numEntries)
                {
                    break;
                }
                entryCnt++;

                JsonObject entry = new JsonObject();
                entry.Put("Title", e.Title);
                entry.Put("Link", e.Links);
                if (getSummaries)
                {
                    entry.Put("Summary", e.Summary);
                }
                if (e.LastUpdatedTime == e.PublishDate)
                {
                    entry.Put("Date", e.PublishDate.LocalDateTime.ToShortDateString());
                }
                else
                {
                    entry.Put("Date", e.LastUpdatedTime.LocalDateTime.ToShortDateString());
                }

                // if no author at feed level, use the first entry author
                if (jsonAuthor == null && e.Authors.Count != 0)
                {
                    jsonAuthor = e.Authors[0].Name;
                }

                entries.Put(entry);
            }

            json.Put("Author", jsonAuthor ?? "");
            reader.Close();
            return(json);
        }
Пример #13
0
        public void ProcessRequest(HttpContext context)
        {
            //Process authorization
            if (!ProcessAuthorization(context))
            {
                AccessDenied(context);
                return;
            }
            var productId    = Helpers.ParseGuid(context.Request[ProductParam]);
            var moduleIds    = Helpers.ParseGuids(context.Request[ModuleParam]);
            var actionType   = Helpers.ParseInt(context.Request[ActionTypeParam]);
            var containerIds = Helpers.Tokenize(context.Request[ContainerParam]);
            var title        = context.Request[TitleParam];

            if (string.IsNullOrEmpty(title))
            {
                title = Resources.Resource.RecentActivity;
            }
            var userIds = Helpers.ParseGuid(context.Request[UserParam]);

            if (userIds.HasValue)
            {
                throw new NotImplementedException();
            }

            var userActivity = UserActivityManager.GetUserActivities(
                TenantProvider.CurrentTenantID,
                null,
                productId.GetValueOrDefault(),
                moduleIds,
                actionType.GetValueOrDefault(),
                containerIds,
                0, 100);

            var feedItems = userActivity.Select(x =>
            {
                var user        = CoreContext.UserManager.GetUsers(x.UserID);
                var veloContext = Formatter.PrepareContext(x, user);
                var item        = new SyndicationItem(
                    HttpUtility.HtmlDecode(Formatter.Format(context, "title.txt", veloContext)),
                    SyndicationContent.CreateHtmlContent(Formatter.Format(context, "pattern.html", veloContext)),
                    new Uri(CommonLinkUtility.GetFullAbsolutePath(x.URL)),
                    x.ID.ToString(),
                    new DateTimeOffset(TenantUtil.DateTimeToUtc(x.Date)))
                {
                    PublishDate = x.Date,
                    Summary     = SyndicationContent.CreatePlaintextContent(Formatter.Format(context, "pattern.txt", veloContext))
                };
                var person = new SyndicationPerson(user.Email)
                {
                    Name = user.UserName
                };
                if (productId.HasValue)
                {
                    person.Uri = CommonLinkUtility.GetUserProfile(user.ID, productId.Value);
                }
                item.Authors.Add(person);
                return(item);
            });

            var lastUpdate = new DateTimeOffset(DateTime.UtcNow);

            if (userActivity.Count > 0)
            {
                lastUpdate = new DateTimeOffset(userActivity.Max(x => x.Date));
            }

            var feed = new SyndicationFeed(
                title,
                Resources.Resource.RecentActivity,
                new Uri(context.Request.GetUrlRewriter(), VirtualPathUtility.ToAbsolute(Studio.WhatsNew.PageUrl)),
                TenantProvider.CurrentTenantID.ToString(),
                lastUpdate, feedItems);

            var rssFormatter = new Atom10FeedFormatter(feed);

            //Set writer settings
            var settings = new XmlWriterSettings();

            settings.CheckCharacters  = false;
            settings.ConformanceLevel = ConformanceLevel.Document;
            settings.Encoding         = Encoding.UTF8;
            settings.Indent           = true;


            using (var writer = XmlWriter.Create(context.Response.Output, settings))
            {
                rssFormatter.WriteTo(writer);
            }
            context.Response.Charset     = Encoding.UTF8.WebName;
            context.Response.ContentType = "application/atom+xml";
        }
Пример #14
0
        public string GetUserPostsRss(long UserID)
        {
            var             User = _context.Users.Find(UserID);
            SyndicationFeed feed = new SyndicationFeed("Feed Title", "Feed Description", new Uri("http://jamespritts.com"), "FeedID", DateTime.Now);
            // Add a custom attribute.
            XmlQualifiedName xqName = new XmlQualifiedName("GameBeOkKey");

            feed.AttributeExtensions.Add(xqName, "codeHard1");

            SyndicationPerson sp = new SyndicationPerson(User.Email, User.UserName, $"http://jamespritts.com/u/{User.UserName}");

            feed.Authors.Add(sp);

            SyndicationCategory category = new SyndicationCategory("FeedCategory", "CategoryScheme", "CategoryLabel");

            feed.Categories.Add(category);

            feed.Contributors.Add(new SyndicationPerson("*****@*****.**", "James Pritts", "http://jamespritts.com"));
            feed.Copyright   = new TextSyndicationContent($"Copyright {DateTime.Now.Year}");
            feed.Description = new TextSyndicationContent("Personal Post Feed");

            // Add a custom element.
            XmlDocument doc         = new XmlDocument();
            XmlElement  feedElement = doc.CreateElement("CustomElement");

            feedElement.InnerText = "Some text";
            feed.ElementExtensions.Add(feedElement);

            feed.Generator = "GameBeOk User Rss Feed";
            feed.Id        = "FeedID";
            feed.ImageUrl  = new Uri("http://server/image.jpg");

            var userPosts = _context.Posts.Where(x => x.Sender == User.Email);

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

            foreach (var v in userPosts)
            {
                TextSyndicationContent textContent = new TextSyndicationContent(v.Content);
                SyndicationItem        item        = new SyndicationItem("User Post", textContent, new Uri("http://server/items"), "ItemID", DateTime.Now);

                items.Add(item);
            }

            feed.Items           = items;
            feed.Language        = "en-us";
            feed.LastUpdatedTime = DateTime.Now;

            SyndicationLink link = new SyndicationLink(new Uri("http://server/link"), "alternate", "Link Title", "text/html", 1000);

            feed.Links.Add(link);

            XmlWriter           atomWriter    = XmlWriter.Create("atom.xml");
            Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(feed);

            atomFormatter.WriteTo(atomWriter);
            atomWriter.Close();

            using (XmlWriter rssWriter = XmlWriter.Create("rss.xml"))
            {
                Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);
                rssFormatter.WriteTo(rssWriter);
                return(rssWriter.ToString());
            }
        }
Пример #15
0
        public override AtomItem ToAtomItem(NameValueCollection parameters)
        {
            string identifier = this.Identifier;
            string name       = (this.Name != null ? this.Name : this.Identifier);
            string text       = (this.TextContent != null ? this.TextContent : "");

            AtomItem atomEntry  = null;
            var      entityType = EntityType.GetEntityType(typeof(DataPackage));
            Uri      id         = new Uri(context.BaseUrl + "/" + entityType.Keyword + "/search?id=" + this.Identifier);

            try {
                atomEntry = new AtomItem(identifier, name, null, id.ToString(), DateTime.UtcNow);
            } catch (Exception) {
                atomEntry = new AtomItem();
            }

            atomEntry.ElementExtensions.Add("identifier", "http://purl.org/dc/elements/1.1/", this.Identifier);

            atomEntry.Links.Add(new SyndicationLink(id, "self", name, "application/atom+xml", 0));

            UriBuilder search = new UriBuilder(context.BaseUrl + "/" + entityType.Keyword + "/" + (Kind == KINDRESOURCESETUSER ? "default" : identifier) + "/description");

            atomEntry.Links.Add(new SyndicationLink(search.Uri, "search", name, "application/atom+xml", 0));

            search       = new UriBuilder(context.BaseUrl + "/" + entityType.Keyword + "/" + identifier + "/search");
            search.Query = "key=" + this.AccessKey;

            atomEntry.Links.Add(new SyndicationLink(search.Uri, "public", name, "application/atom+xml", 0));
            atomEntry.Links.Add(new SyndicationLink(search.Uri, "alternate", name, "application/atom+xml", 0));

            Uri share = new Uri(context.BaseUrl + "/share?url=" + id.AbsoluteUri);

            atomEntry.Links.Add(new SyndicationLink(share, "via", name, "application/atom+xml", 0));
            atomEntry.ReferenceData = this;

            atomEntry.PublishDate = new DateTimeOffset(this.CreationTime);

            if (Owner != null)
            {
                var basepath = new UriBuilder(context.BaseUrl);
                basepath.Path = "user";
                string            usrUri  = basepath.Uri.AbsoluteUri + "/" + Owner.Username;
                string            usrName = (!String.IsNullOrEmpty(owner.FirstName) && !String.IsNullOrEmpty(Owner.LastName) ? Owner.FirstName + " " + Owner.LastName : Owner.Username);
                SyndicationPerson author  = new SyndicationPerson(null, usrName, usrUri);
                author.ElementExtensions.Add(new SyndicationElementExtension("identifier", "http://purl.org/dc/elements/1.1/", Owner.Username));
                atomEntry.Authors.Add(author);
                atomEntry.Categories.Add(new SyndicationCategory("visibility", null, IsPublic() ? "public" : (IsRestricted() ? "restricted" : "private")));
                if (Kind == KINDRESOURCESETUSER)
                {
                    atomEntry.Categories.Add(new SyndicationCategory("default", null, "true"));
                }

                if (Owner.Id == context.UserId)
                {
                    //for owner only, we give the link to know with who the data package is shared
                    Uri sharedUrl = null;
                    //if shared with users
                    if (IsSharedToUser())
                    {
                        sharedUrl = new Uri(string.Format("{0}/user/search?correlatedTo={1}", context.BaseUrl, HttpUtility.UrlEncode(id.AbsoluteUri)));
                    }
                    else if (IsSharedToCommunity())
                    {
                        sharedUrl = new Uri(string.Format("{0}/community/search?correlatedTo={1}", context.BaseUrl, HttpUtility.UrlEncode(id.AbsoluteUri)));
                    }
                    if (sharedUrl != null)
                    {
                        atomEntry.Links.Add(new SyndicationLink(sharedUrl, "results", name, "application/atom+xml", 0));
                    }
                }
            }

            if (Items == null)
            {
                LoadItems();
            }
            var nbitems = Items == null ? 0 : Items.Count;

            atomEntry.Categories.Add(new SyndicationCategory("nbItems", null, "" + nbitems));

            if (Kind != KINDRESOURCESETNORMAL)
            {
                atomEntry.Categories.Add(new SyndicationCategory("kind", null, Kind == KINDRESOURCESETUSER ? "basket" : "app"));
            }

            return(atomEntry);
        }
Пример #16
0
 public static bool TryParseAttributeEntryPoint(string name, string ns, string value, SyndicationPerson person, string version)
 {
     return(TryParseAttribute(name, ns, value, person, version));
 }
Пример #17
0
 public static bool TryParseElementEntryPoint(XmlReader reader, SyndicationPerson person, string version)
 {
     return(TryParseElement(reader, person, version));
 }
Пример #18
0
        public override AtomItem ToAtomItem(NameValueCollection parameters)
        {
            bool ispublic  = this.Kind == DomainKind.Public;
            bool isprivate = this.Kind == DomainKind.Private;
            bool ishidden  = this.Kind == DomainKind.Hidden;

            bool searchAll = false;

            if (!string.IsNullOrEmpty(parameters["visibility"]))
            {
                switch (parameters["visibility"])
                {
                case "public":
                    if (this.Kind != DomainKind.Public)
                    {
                        return(null);
                    }
                    break;

                case "private":
                    if (this.Kind != DomainKind.Private)
                    {
                        return(null);
                    }
                    break;

                case "hidden":
                    if (this.Kind != DomainKind.Hidden)
                    {
                        return(null);
                    }
                    break;

                case "owned":
                    if (!(context.UserId == this.OwnerId))
                    {
                        return(null);
                    }
                    break;

                case "all":
                    searchAll = true;
                    break;
                }
            }

            //if private or hidden, lets check the current user can access it (have a role in the domain)
            //if private but visibility=all, user can access
            if (ishidden || (isprivate && !searchAll))
            {
                var proles = Role.GetUserRolesForDomain(context, context.UserId, this.Id);
                if (proles == null || proles.Length == 0)
                {
                    return(null);
                }
            }

            var entityType = EntityType.GetEntityType(typeof(Domain));
            Uri id         = new Uri(context.BaseUrl + "/" + entityType.Keyword + "/search?id=" + this.Identifier);

            if (!string.IsNullOrEmpty(parameters["q"]))
            {
                string q = parameters["q"].ToLower();
                if (!this.Identifier.ToLower().Contains(q) && !(Description != null && Description.ToLower().Contains(q)))
                {
                    return(null);
                }
            }

            AtomItem result = new AtomItem();

            result.Id      = id.ToString();
            result.Title   = new TextSyndicationContent(Identifier);
            result.Content = new TextSyndicationContent(Identifier);

            result.ElementExtensions.Add("identifier", "http://purl.org/dc/elements/1.1/", this.Identifier);
            result.Summary       = new TextSyndicationContent(Description);
            result.ReferenceData = this;

            result.PublishDate = new DateTimeOffset(DateTime.UtcNow);

            //members
            var roles = new EntityList <Role>(context);

            roles.Load();
            foreach (var role in roles)
            {
                var usrs = role.GetUsers(this.Id);
                foreach (var usrId in usrs)
                {
                    User usr = User.FromId(context, usrId);
                    SyndicationPerson author = new SyndicationPerson(usr.Email, usr.FirstName + " " + usr.LastName, "");
                    author.ElementExtensions.Add(new SyndicationElementExtension("identifier", "http://purl.org/dc/elements/1.1/", usr.Username));
                    author.ElementExtensions.Add(new SyndicationElementExtension("role", "http://purl.org/dc/elements/1.1/", role.Identifier));
                    result.Authors.Add(author);
                }
            }

            result.Links.Add(new SyndicationLink(id, "self", Identifier, "application/atom+xml", 0));
            if (!string.IsNullOrEmpty(IconUrl))
            {
                Uri uri;
                if (IconUrl.StartsWith("http"))
                {
                    uri = new Uri(IconUrl);
                }
                else
                {
                    var urib = new UriBuilder(System.Web.HttpContext.Current.Request.Url);
                    urib.Path = IconUrl;
                    uri       = urib.Uri;
                }

                result.Links.Add(new SyndicationLink(uri, "icon", "", GetImageMimeType(IconUrl), 0));
            }

            result.Categories.Add(new SyndicationCategory("visibility", null, ispublic ? "public" : isprivate ? "private" : "hidden"));

            return(result);
        }
Пример #19
0
 public void WriteElementExtensionsEntryPoint(XmlWriter writer, SyndicationPerson person, string version)
 {
     WriteElementExtensions(writer, person, version);
 }
Пример #20
0
        public static void SyndicationFeed_Write_RSS_Atom()
        {
            string RssPath  = Path.GetTempFileName();
            string AtomPath = Path.GetTempFileName();

            try
            {
                // *** SETUP *** \\
                SyndicationFeed   feed = new SyndicationFeed("Contoso News", "<div>Most recent news from Contoso</div>", new Uri("http://www.Contoso.com/news"), "123FeedID", DateTime.Now);
                CancellationToken ct   = new CancellationToken();

                //Add an author
                SyndicationPerson author = new SyndicationPerson("*****@*****.**");
                feed.Authors.Add(author);

                //Create item
                SyndicationItem item1 = new SyndicationItem("SyndicationFeed released for .net Core", "A lot of text describing the release of .net core feature", new Uri("http://Contoso.com/news/path"));

                //Add item to feed
                List <SyndicationItem> feedList = new List <SyndicationItem> {
                    item1
                };
                feed.Items = feedList;
                feed.ElementExtensions.Add("CustomElement", "", "asd");

                //add an image
                feed.ImageUrl = new Uri("http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg");
                //feed.ImageTitle = new TextSyndicationContent("Titulo loco");

                feed.BaseUri = new Uri("http://mypage.com");

                // Write to XML > rss

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Async = true;

                XmlWriter          xmlwRss = XmlWriter.Create(RssPath, settings);
                Rss20FeedFormatter rssff   = new Rss20FeedFormatter(feed);

                // Write to XML > atom

                XmlWriter           xmlwAtom = XmlWriter.Create(AtomPath);
                Atom10FeedFormatter atomf    = new Atom10FeedFormatter(feed);


                // *** EXECUTE *** \\
                Task rss = rssff.WriteToAsync(xmlwRss, ct);
                Task.WaitAll(rss);

                xmlwRss.Close();

                atomf.WriteToAsync(xmlwAtom, ct).GetAwaiter().GetResult();;
                xmlwAtom.Close();

                // *** ASSERT *** \\
                Assert.True(File.Exists(RssPath));
                Assert.True(File.Exists(AtomPath));
            }
            finally
            {
                // *** CLEANUP *** \\
                File.Delete(RssPath);
                File.Delete(AtomPath);
            }
        }
Пример #21
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);
        }
Пример #22
0
        static void Snippet0()
        {
            // <Snippet0>
            // <Snippet49>
            SyndicationFeed feed = new SyndicationFeed("Feed Title", "Feed Description", new Uri("http://Feed/Alternate/Link"), "FeedID", DateTime.Now);
            // </Snippet49>
            // Add a custom attribute.
            XmlQualifiedName xqName = new XmlQualifiedName("CustomAttribute");

            feed.AttributeExtensions.Add(xqName, "Value");

            SyndicationPerson sp = new SyndicationPerson("*****@*****.**", "Jesper Aaberg", "http://Jesper/Aaberg");

            feed.Authors.Add(sp);

            SyndicationCategory category = new SyndicationCategory("FeedCategory", "CategoryScheme", "CategoryLabel");

            feed.Categories.Add(category);

            feed.Contributors.Add(new SyndicationPerson("*****@*****.**", "Lene Aaling", "http://lene/aaling"));
            feed.Copyright   = new TextSyndicationContent("Copyright 2007");
            feed.Description = new TextSyndicationContent("This is a sample feed");

            // Add a custom element.
            XmlDocument doc         = new XmlDocument();
            XmlElement  feedElement = doc.CreateElement("CustomElement");

            feedElement.InnerText = "Some text";
            feed.ElementExtensions.Add(feedElement);

            feed.Generator = "Sample Code";
            feed.Id        = "FeedID";
            feed.ImageUrl  = new Uri("http://server/image.jpg");

            TextSyndicationContent textContent = new TextSyndicationContent("Some text content");
            SyndicationItem        item        = new SyndicationItem("Item Title", textContent, new Uri("http://server/items"), "ItemID", DateTime.Now);

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

            items.Add(item);
            feed.Items = items;

            feed.Language        = "en-us";
            feed.LastUpdatedTime = DateTime.Now;

            SyndicationLink link = new SyndicationLink(new Uri("http://server/link"), "alternate", "Link Title", "text/html", 1000);

            feed.Links.Add(link);

            XmlWriter           atomWriter    = XmlWriter.Create("atom.xml");
            Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(feed);

            atomFormatter.WriteTo(atomWriter);
            atomWriter.Close();

            XmlWriter          rssWriter    = XmlWriter.Create("rss.xml");
            Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);

            rssFormatter.WriteTo(rssWriter);
            rssWriter.Close();

            // </Snippet0>
        }
        public async Task ShouldGenerateBlogRss()
        {
            var projectInfo = this.TestContext.ShouldGetProjectDirectoryInfo(this.GetType());

            #region test properties:

            var blobContainerName        = this.TestContext.Properties["blobContainerName"].ToString();
            var blobContainerNameClassic = this.TestContext.Properties["blobContainerNameClassic"].ToString();

            var rssPath = this.TestContext.Properties["rssPath"].ToString();
            rssPath = projectInfo.ToCombinedPath(rssPath);
            this.TestContext.ShouldFindFile(rssPath);

            #endregion

            var containerClassic = cloudStorageAccountClassic.CreateCloudBlobClient().GetContainerReference(blobContainerNameClassic);
            var keys             = new AzureBlobKeys();
            keys.Add <BlogEntry>(i => i.Slug);

            var repository = new BlogRepository(keys, containerClassic);
            var data       = await(repository as IBlogEntryIndex).GetIndexAsync();
            Assert.IsTrue(data.Any(), "The expected data are not here.");

            var feed = data
                       .OrderByDescending(i => i.InceptDate)
                       .Take(10);

            var builder  = new StringBuilder();
            var settings = new XmlWriterSettings
            {
                Async              = true,
                CloseOutput        = true,
                Encoding           = Encoding.UTF8,
                Indent             = true,
                OmitXmlDeclaration = true
            };
            var person = new SyndicationPerson("Bryan Wilhite", "*****@*****.**");

            using (var writer = XmlWriter.Create(builder, settings))
            {
                var feedWriter = new RssFeedWriter(writer);

                await feedWriter.WritePubDate(DateTime.Now);

                await feedWriter.WriteTitle($">DayPath_");

                await feedWriter.WriteDescription($"The technical journey of @BryanWilhite.");

                await feedWriter.WriteCopyright($"Bryan Wilhite, Songhay System {DateTime.Now.Year}");

                await feedWriter.Write(new SyndicationLink(new Uri("http://songhayblog.azurewebsites.net", UriKind.Absolute)));

                var tasks = feed.Select(async entry =>
                {
                    var item = new SyndicationItem
                    {
                        Description = entry.Content,
                        Id          = entry.Slug,
                        LastUpdated = entry.ModificationDate,
                        Published   = entry.InceptDate,
                        Title       = entry.Title
                    };

                    item.AddContributor(person);
                    item.AddLink(new SyndicationLink(new Uri($"http://songhayblog.azurewebsites.net/blog/entry/{entry.Slug}", UriKind.Absolute)));

                    await feedWriter.Write(item);
                });

                await Task.WhenAll(tasks);

                await writer.FlushAsync();
            }

            File.WriteAllText(rssPath, builder.ToString());

            var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference(blobContainerName);
            await container.UploadBlobAsync(rssPath, string.Empty);
        }
Пример #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ContentQuery contentQuery = new ContentQuery
            {
                ContentTypeID            = (int)SueetieContentType.BlogPost,
                CacheMinutes             = 5,
                SueetieContentViewTypeID = (int)SueetieContentViewType.AggregateBlogPostList
            };
            List <SueetieBlogPost> sueetieBlogPosts = SueetieBlogs.GetSueetieBlogPostList(contentQuery);
            var dataItems = from post in sueetieBlogPosts
                            orderby post.DateCreated descending
                            select post;

            const int maxItemsInFeed = 10;

            // Determine whether we're outputting an Atom or RSS feed
            bool outputAtom = (Request.QueryString["Type"] == "ATOM");
            bool outputRss  = !outputAtom;

            if (outputRss)
            {
                Response.ContentType = "application/rss+xml";
            }
            else if (outputAtom)
            {
                Response.ContentType = "application/atom+xml";
            }

            // Create the feed and specify the feed's attributes
            SyndicationFeed myFeed = new SyndicationFeed();

            myFeed.Title       = TextSyndicationContent.CreatePlaintextContent("Most Recent Posts on " + SiteSettings.Instance.SiteName);
            myFeed.Description = TextSyndicationContent.CreatePlaintextContent("A syndication of the most recently published posts on " + SiteSettings.Instance.SiteName);
            myFeed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(GetFullyQualifiedUrl("~/Default.aspx"))));
            myFeed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(GetFullyQualifiedUrl(Request.RawUrl))));
            myFeed.Copyright = TextSyndicationContent.CreatePlaintextContent("Copyright " + SiteSettings.Instance.SiteName);
            myFeed.Language  = "en-us";

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

            foreach (SueetieBlogPost p in dataItems.Take(maxItemsInFeed))
            {
                if (outputAtom && p.Author == null)
                {
                    continue;
                }

                SyndicationItem item = new SyndicationItem();
                item.Title = TextSyndicationContent.CreatePlaintextContent(p.BlogTitle + " - " + p.Title);
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(GetFullyQualifiedUrl(p.Permalink))));
                item.Summary = TextSyndicationContent.CreateHtmlContent(p.PostContent);
                item.Categories.Add(new SyndicationCategory(p.BlogTitle));
                item.PublishDate = p.DateCreated;
                item.Id          = GetFullyQualifiedUrl(p.Permalink);
                SyndicationPerson authInfo = new SyndicationPerson();
                authInfo.Email = p.Email;
                authInfo.Name  = p.DisplayName;
                item.Authors.Add(authInfo);

                feedItems.Add(item);
            }

            myFeed.Items = feedItems;

            XmlWriterSettings outputSettings = new XmlWriterSettings();

            outputSettings.Indent = true;
            XmlWriter feedWriter = XmlWriter.Create(Response.OutputStream, outputSettings);

            if (outputAtom)
            {
                Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(myFeed);
                atomFormatter.WriteTo(feedWriter);
            }
            else if (outputRss)
            {
                Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(myFeed);
                rssFormatter.WriteTo(feedWriter);
            }

            feedWriter.Close();
        }
Пример #25
0
        public JsonResult Feed()
        {
            SyndicationFeed feed = new SyndicationFeed("Les graines de l'info", "Ce feed RSS comporte les dernières graines de l'info", new Uri("http://Feed/Alternate/Link"), "FeedID", DateTime.Now);
            // Add a custom attribute.
            XmlQualifiedName xqName = new XmlQualifiedName("CustomAttribute");

            feed.AttributeExtensions.Add(xqName, "Value");

            SyndicationPerson sp = new SyndicationPerson("*****@*****.**", "Nom Prenom", "http://nom/prenom");

            feed.Authors.Add(sp);

            SyndicationCategory category = new SyndicationCategory("FeedCategory", "CategoryScheme", "CategoryLabel");

            feed.Categories.Add(category);

            feed.Contributors.Add(new SyndicationPerson("*****@*****.**", "Prenom Nom", "http://prenom/nom"));
            feed.Copyright   = new TextSyndicationContent("Copyright 2007");
            feed.Description = new TextSyndicationContent("This is a sample feed");

            // Add a custom element.
            XmlDocument doc         = new XmlDocument();
            XmlElement  feedElement = doc.CreateElement("CustomElement");

            feedElement.InnerText = "Some text";
            feed.ElementExtensions.Add(feedElement);

            feed.Generator = "Sample Code";
            feed.Id        = "FeedID";
            feed.ImageUrl  = new Uri("http://server/image.jpg");

            TextSyndicationContent textContent = new TextSyndicationContent("Some text content");
            SyndicationItem        item        = new SyndicationItem("Item Title", textContent, new Uri("http://server/items"), "ItemID", DateTime.Now);

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

            items.Add(item);
            feed.Items = items;

            feed.Language        = "en-us";
            feed.LastUpdatedTime = DateTime.Now;

            SyndicationLink link = new SyndicationLink(new Uri("http://server/link"), "alternate", "Link Title", "text/html", 1000);

            feed.Links.Add(link);

            using (var sw = new StringWriter())
            {
                using (var rssWriter = XmlWriter.Create(sw))
                {
                    //XmlWriter atomWriter = XmlWriter.Create("atom.xml");
                    //Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(feed);
                    //atomFormatter.WriteTo(atomWriter);
                    //atomWriter.Close();

                    Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);
                    rssFormatter.WriteTo(rssWriter);
                    rssWriter.Close();
                }
                return(Json(sw.ToString()));
            }
        }
Пример #26
0
        private static async Task <List <SyndicationItem> > GetAtomItemsForBlogger(Blogger blogger, HttpClient client)
        {
            var atomItems = new List <SyndicationItem>();
            // parse Atom feed
            var atomResponse = await client.GetAsync(blogger.BlogfeedUrl);

            var atomStream = await atomResponse.Content.ReadAsStreamAsync();

            var atomStreamReader = new StreamReader(atomStream, Encoding.UTF8);

            var atomReader     = XmlReader.Create(atomStreamReader);
            var atomSerializer = new Atom10FeedFormatter();

            atomSerializer.ReadFrom(atomReader);
            var atomFeed = atomSerializer.Feed;

            foreach (var item in atomFeed.Items)
            {
                var newItem = new SyndicationItem
                {
                    BaseUri         = item.BaseUri,
                    Content         = item.Content,
                    Id              = item.Id,
                    LastUpdatedTime = item.LastUpdatedTime
                };

                foreach (var link in item.Links)
                {
                    newItem.Links.Add(link);
                }
                newItem.PublishDate = item.PublishDate;
                newItem.Summary     = item.Summary;
                newItem.Title       = item.Title;

                var copyright =
                    new TextSyndicationContent(blogger.Name);

                newItem.Copyright = copyright;


                if (item.ElementExtensions.Count > 0)
                {
                    var reader = item.ElementExtensions.GetReaderAtElementExtensions();
                    while (reader.Read())
                    {
                        if ("content:encoded" == reader.Name)
                        {
                            SyndicationContent content =
                                SyndicationContent.CreatePlaintextContent(reader.ReadString());
                            newItem.Content = content;
                        }
                    }
                }


                // assign author name explicitly because email is
                // used by default
                var author = new SyndicationPerson {
                    Name = blogger.Name
                };
                newItem.Authors.Add(author);

                newItem.Contributors.Add(author);

                var doc     = new XmlDocument();
                var creator = String.Format(
                    "<dc:creator xmlns:dc=\"http://purl.org/dc/elements/1.1/\">{0}</dc:creator>",
                    blogger.Name);
                doc.LoadXml(creator);
                var insertext = new SyndicationElementExtension(new XmlNodeReader(doc.DocumentElement));

                newItem.ElementExtensions.Add(insertext);

                atomItems.Add(newItem);
            }
            return(atomItems);
        }
Пример #27
0
 public SyndicationPersonSubclass(SyndicationPerson source) : base(source)
 {
 }
Пример #28
0
 public static void LoadElementExtensionsEntryPoint(XmlReader reader, SyndicationPerson person, int maxExtensionSize) => LoadElementExtensions(reader, person, maxExtensionSize);
Пример #29
0
        static void Main(string[] args)
        {
            SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2011");

            ContentManager cm = new ContentManager(client);

            List <Source> sources      = cm.GetSources();
            int           countSources = sources.Count;

            Console.WriteLine("Loaded " + countSources + " sources. Starting to process.");
            XmlNamespaceManager nm = new XmlNamespaceManager(new NameTable());

            nm.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

            Dictionary <Source, List <Article> > addedContent = new Dictionary <Source, List <Article> >();

            foreach (var source in sources)
            {
                Console.WriteLine("Loading content for source " + source.Title);
                XmlDocument feedXml = null;

                WebRequest wrq = WebRequest.Create(source.RssFeedUrl);
                wrq.Proxy             = WebRequest.DefaultWebProxy;
                wrq.Proxy.Credentials = CredentialCache.DefaultCredentials;

                XmlTextReader reader = null;
                try
                {
                    reader = new XmlTextReader(wrq.GetResponse().GetResponseStream());
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Could not read response from source" + ex.Message);
                }
                if (reader == null)
                {
                    continue;
                }

                SyndicationFeed feed = SyndicationFeed.Load(reader);

                int countItems = feed.Items.Count();
                Console.WriteLine("Loaded " + countItems + " items from source. Processing");
                int            count       = 0;
                List <Article> newArticles = new List <Article>();
                foreach (var item in feed.Items)
                {
                    count++;
                    Person author = null;
                    if (item.Authors.Count == 0)
                    {
                        //Console.WriteLine("Could not find an author in feed source, checking for default");
                        if (source.DefaultAuthor != null)
                        {
                            author = source.DefaultAuthor;
                            //Console.WriteLine("Using default author " + author.Name);
                        }
                        else
                        {
                            //Console.WriteLine("Could not find default author, being creative");
                            if (feedXml == null)
                            {
                                try
                                {
                                    feedXml = new XmlDocument();
                                    feedXml.Load(source.RssFeedUrl);
                                }catch (Exception ex)
                                {
                                    Console.WriteLine("Something went wrong loading " + source.RssFeedUrl);
                                    Console.WriteLine(ex.ToString());
                                }
                            }
                            if (feedXml != null)
                            {
                                string xpath = "/rss/channel/item[" + count + "]/dc:creator";
                                if (feedXml.SelectSingleNode(xpath, nm) != null)
                                {
                                    author =
                                        cm.FindPersonByNameOrAlternate(feedXml.SelectSingleNode(xpath, nm).InnerText);
                                    if (author == null)
                                    {
                                        author = new Person(client)
                                        {
                                            Name = feedXml.SelectSingleNode(xpath, nm).InnerText
                                        };
                                        author.Save();
                                        author =
                                            cm.FindPersonByNameOrAlternate(
                                                feedXml.SelectSingleNode(xpath, nm).InnerText, true);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        string            nameOrAlternate;
                        SyndicationPerson syndicationPerson = item.Authors.First();
                        if (string.IsNullOrEmpty(syndicationPerson.Name))
                        {
                            nameOrAlternate = syndicationPerson.Email;
                        }
                        else
                        {
                            nameOrAlternate = syndicationPerson.Name;
                        }

                        author = cm.FindPersonByNameOrAlternate(nameOrAlternate);
                    }
                    if (author == null)
                    {
                        string name = string.Empty;
                        if (item.Authors.Count > 0)
                        {
                            if (item.Authors[0].Name != null)
                            {
                                name = item.Authors[0].Name;
                            }
                            else
                            {
                                name = item.Authors[0].Email;
                            }
                        }
                        author = new Person(client)
                        {
                            Name = name
                        };
                        if (source.IsStackOverflow)
                        {
                            author.StackOverflowId = item.Authors[0].Uri;
                        }
                        author.Save();
                        author = cm.FindPersonByNameOrAlternate(name, true);
                    }

                    List <Person> authors = new List <Person>();
                    authors.Add(author);
                    //Console.WriteLine("Using author: " + author.Name);

                    if (source.IsStackOverflow)
                    {
                        if (string.IsNullOrEmpty(author.StackOverflowId))
                        {
                            author.StackOverflowId = item.Authors[0].Uri;
                            author.Save(true);
                        }
                    }

                    if (item.PublishDate.DateTime > DateTime.MinValue)
                    {
                        // Organize content by Date
                        // Year
                        // Month
                        // Day
                        string store = cm.GetFolderForDate(item.PublishDate.DateTime);
                        string articleTitle;
                        if (string.IsNullOrEmpty(item.Title.Text))
                        {
                            articleTitle = "No title specified";
                        }
                        else
                        {
                            articleTitle = item.Title.Text;
                        }
                        articleTitle = articleTitle.Trim();

                        OrganizationalItemItemsFilterData filter = new OrganizationalItemItemsFilterData();
                        bool alreadyExists = false;
                        foreach (XElement node in client.GetListXml(store, filter).Nodes())
                        {
                            if (!node.Attribute("Title").Value.Equals(articleTitle))
                            {
                                continue;
                            }
                            alreadyExists = true;
                            break;
                        }
                        if (!alreadyExists)
                        {
                            //Console.WriteLine(articleTitle + " is a new article. Saving");
                            Console.Write(".");
                            Article article = new Article(client, new TcmUri(store));

                            string content = "";
                            string summary = "";
                            try
                            {
                                if (item.Content != null)
                                {
                                    content = ((TextSyndicationContent)item.Content).Text;
                                }
                                if (item.Summary != null)
                                {
                                    summary = item.Summary.Text;
                                }
                                if (!string.IsNullOrEmpty(content))
                                {
                                    try
                                    {
                                        content = Utilities.ConvertHtmlToXhtml(content);
                                    }
                                    catch (Exception)
                                    {
                                        content = null;
                                    }
                                }
                                if (!string.IsNullOrEmpty(summary))
                                {
                                    try
                                    {
                                        summary = Utilities.ConvertHtmlToXhtml(summary);
                                    }
                                    catch (Exception)
                                    {
                                        summary = null;
                                    }
                                }

                                if (string.IsNullOrEmpty(summary))
                                {
                                    summary = !string.IsNullOrEmpty(content) ? content : "Could not find summary";
                                }
                                if (string.IsNullOrEmpty(content))
                                {
                                    content = !string.IsNullOrEmpty(summary) ? summary : "Could not find content";
                                }
                            }
                            catch (Exception ex)
                            {
                                content  = "Could not convert source description to XHtml. " + ex.Message;
                                content += ((TextSyndicationContent)item.Content).Text;
                            }
                            article.Authors      = authors;
                            article.Body         = content;
                            article.Date         = item.PublishDate.DateTime;
                            article.DisplayTitle = item.Title.Text;
                            article.Title        = articleTitle;
                            article.Summary      = summary;
                            article.Url          = item.Links.First().Uri.AbsoluteUri;
                            List <string> categories = new List <string>();
                            foreach (var category in item.Categories)
                            {
                                categories.Add(category.Name);
                            }
                            article.Categories = categories;
                            article.Source     = source;
                            article.Save();
                            newArticles.Add(article);
                        }
                    }
                }
                if (newArticles.Count > 0)
                {
                    addedContent.Add(source, newArticles);
                }
            }
            List <string> idsToPublish = new List <string>();

            if (addedContent.Count > 0)
            {
                Console.WriteLine("============================================================");
                Console.WriteLine("Added content");
                foreach (Source source in addedContent.Keys)
                {
                    string sg = cm.GetStructureGroup(source.Title, cm.ResolveUrl(Constants.RootStructureGroup));
                    Console.WriteLine("Source: " + source.Content.Title + "(" + addedContent[source].Count + ")");
                    foreach (Article article in addedContent[source])
                    {
                        string yearSg = cm.GetStructureGroup(article.Date.Year.ToString(CultureInfo.InvariantCulture), sg);
                        string pageId = cm.AddToPage(yearSg, article);
                        if (!idsToPublish.Contains(pageId))
                        {
                            idsToPublish.Add(pageId);
                        }
                        Console.WriteLine(article.Title + ", " + article.Authors[0].Name);
                    }
                    Console.WriteLine("-------");
                }
                Console.WriteLine("============================================================");
            }

            // Publishing
            //cm.Publish(idsToPublish.ToArray(), "tcm:0-2-65537");


            Console.WriteLine("Finished, press any key to exit");
            Console.Read();
        }
        public static SyndicationPerson SyndicationPersonFromJTokenList(JToken person, string prefix = "")
        {
            if (person.SelectToken("name") != null) {

                SyndicationPerson sp = new SyndicationPerson();

                foreach (var child in person.Children<JProperty>()) {
                    if (child.Name == "uri") {
                        sp.Uri = child.Value.ToString();
                        continue;
                    }
                    if (child.Name == "email") {
                        sp.Email = (string)child.Value.ToString();
                        continue;
                    }
                    if (child.Name == "name") {
                        sp.Name = (string)child.Value.ToString();
                        continue;
                    }

                    var xmlReader = JsonConvert.DeserializeXNode("{" + child.ToString() + "}").CreateReader();
                    sp.ElementExtensions.Add(new SyndicationElementExtension(xmlReader));
                }

                return sp;
            }
            throw new ArgumentException("Not a link");
        }