Exemplo n.º 1
0
 private bool TestFileLink(SyndicationLink link)
 {
     return(File.Exists(link.Uri.AbsolutePath));
 }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the feed containing meta data about the feed and the feed entries.
        /// </summary>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> signifying if the request is cancelled.</param>
        /// <returns>A <see cref="SyndicationFeed"/>.</returns>
        public async Task <SyndicationFeed> GetFeed(CancellationToken cancellationToken)
        {
            SyndicationFeed feed = new SyndicationFeed()
            {
                // id (Required) - The feed universally unique identifier.
                Id = FeedId,
                // title (Required) - Contains a human readable title for the feed. Often the same as the title of the
                //                    associated website. This value should not be blank.
                Title = SyndicationContent.CreatePlaintextContent("ASP.NET MVC Boilerplate"),
                // items (Required) - The items to add to the feed.
                Items = await this.GetItems(cancellationToken),
                // subtitle (Recommended) - Contains a human-readable description or subtitle for the feed.
                Description = SyndicationContent.CreatePlaintextContent(
                    "This is the ASP.NET MVC Boilerplate feed description."),
                // updated (Optional) - Indicates the last time the feed was modified in a significant way.
                LastUpdatedTime = DateTimeOffset.Now,
                // logo (Optional) - Identifies a larger image which provides visual identification for the feed.
                //                   Images should be twice as wide as they are tall.
                ImageUrl = new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-logo-96x48.png")),
                // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the feed.
                Copyright = SyndicationContent.CreatePlaintextContent(
                    string.Format("© {0} - {1}", DateTime.Now.Year, Application.Name)),
                // lang (Optional) - The language of the feed.
                Language = "en-GB",
                // generator (Optional) - Identifies the software used to generate the feed, for debugging and other
                //                        purposes. Do not put in anything that identifies the technology you are using.
                // Generator = "Sample Code",
                // base (Buggy) - Add the full base URL to the site so that all other links can be relative. This is
                //                great, except some feed readers are buggy with it, INCLUDING FIREFOX!!!
                //                (See https://bugzilla.mozilla.org/show_bug.cgi?id=480600).
                // BaseUri = new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex))
            };

            // self link (Required) - The URL for the syndication feed.
            feed.Links.Add(SyndicationLink.CreateSelfLink(
                               new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetFeed)),
                               ContentType.Atom));

            // alternate link (Recommended) - The URL for the web page showing the same data as the syndication feed.
            feed.Links.Add(SyndicationLink.CreateAlternateLink(
                               new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)),
                               ContentType.Html));

            // hub link (Recommended) - The URL for the PubSubHubbub hub. Used to push new entries to subscribers
            //                          instead of making them poll the feed. See feed updated method below.
            feed.Links.Add(new SyndicationLink(new Uri(PubSubHubbubHubUrl), "hub", null, null, 0));

            // first, last, next previous (Optional) - Atom 1.0 supports paging of your feed. This is good if your feed
            //                                         becomes very large and needs splitting up into pages. To add
            //                                         paging, you must add links to the first, last, next and previous
            //                                         feed pages.
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed"), "first", null, null, 0));
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=10"), "last", null, null, 0));
            // if ([HAS_PREVIOUS_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=1")), "previous", null, null, 0));
            // if ([HAS_NEXT_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=3"), "next", null, null, 0));

            // author (Recommended) - Names one author of the feed. A feed may have multiple author elements. A feed
            //                        must contain at least one author element unless all of the entry elements contain
            //                        at least one author element.
            feed.Authors.Add(this.GetPerson());

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

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

            // icon (Optional) - Identifies a small image which provides iconic visual identification for the feed.
            //                   Icons should be square.
            feed.SetIcon(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"));

            // Add the Yahoo Media namespace (xmlns:media="http://search.yahoo.com/mrss/") to the Atom feed.
            // This gives us extra abilities, like the ability to give thumbnail images to entries.
            // See http://www.rssboard.org/media-rss for more information.
            feed.AddYahooMediaNamespace();

            return(feed);
        }
 public void GetAbsoluteUri_Invoke_ReturnsExpected(SyndicationLink link, Uri expected)
 {
     Assert.Equal(expected, link.GetAbsoluteUri());
 }
Exemplo n.º 4
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>
        }
Exemplo n.º 5
0
        private SyndicationItem GetSyndicationItem(Store store, Content product, Category category, int description, String type)
        {
            if (category == null)
            {
                return(null);
            }

            if (description == 0)
            {
                description = 300;
            }

            var    productDetailLink = LinkHelper.GetContentLink(product, category.Name, type);
            String detailPage        = String.Format("http://{0}{1}", store.Domain.ToLower(), productDetailLink);

            string desc = "";

            if (description > 0)
            {
                desc = GeneralHelper.GeneralHelper.GetDescription(product.Description, description);
            }
            var uri = new Uri(detailPage);
            var si  = new SyndicationItem(product.Name, desc, uri);

            si.ElementExtensions.Add("guid", String.Empty, uri);
            if (product.UpdatedDate != null)
            {
                si.PublishDate = product.UpdatedDate.Value.ToUniversalTime();
            }


            if (!String.IsNullOrEmpty(category.Name))
            {
                si.ElementExtensions.Add(type + ":category", String.Empty, category.Name);
            }



            if (product.ContentFiles.Any())
            {
                var mainImage = product.ContentFiles.FirstOrDefault(r => r.IsMainImage);
                if (mainImage == null)
                {
                    mainImage = product.ContentFiles.FirstOrDefault();
                }

                if (mainImage != null)
                {
                    string imageSrc = LinkHelper.GetImageLink("Thumbnail", mainImage.FileManager, this.ImageWidth, this.ImageHeight);
                    if (!string.IsNullOrEmpty(imageSrc))
                    {
                        try
                        {
                            SyndicationLink imageLink =
                                SyndicationLink.CreateMediaEnclosureLink(new Uri(imageSrc), "image/jpeg", 100);
                            si.Links.Add(imageLink);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            }

            return(si);
        }
        public void Length_SetNegative_ThrowsArgumentOutOfRangeException()
        {
            var link = new SyndicationLink();

            AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => link.Length = -1);
        }
Exemplo n.º 7
0
 public static void Snippet4()
 {
     // <Snippet4>
     SyndicationLink link = SyndicationLink.CreateAlternateLink(new Uri("http://server/link"));
     // </Snippet4>
 }
Exemplo n.º 8
0
        private Action <Stream> GetXmlContents(IEnumerable <Post> model)
        {
            var items = new List <SyndicationItem>();

            foreach (var post in model)
            {
                // Replace all relative urls with full urls.
                var newHtml = Regex.Replace(post.Content, UrlRegex, m => siteUrl.TrimEnd('/') + "/" + m.Value.TrimStart('/'));

                var item = new SyndicationItem(
                    post.Title,
                    newHtml,
                    new Uri(siteUrl + post.Url)
                    )
                {
                    Id = siteUrl + post.Url,
                    LastUpdatedTime = post.Date.ToUniversalTime(),
                    PublishDate     = post.Date.ToUniversalTime(),
                    Content         = new TextSyndicationContent(post.Content, TextSyndicationContentKind.Html),
                    Summary         = new TextSyndicationContent(post.ContentExcerpt, TextSyndicationContentKind.Html),
                };

                items.Add(item);
            }

            var feed = new SyndicationFeed(
                AtomTitle,
                AtomTitle, /* Using Title also as Description */
                new Uri(siteUrl + "/" + feedfileName),
                items)
            {
                Id = siteUrl + "/",
                LastUpdatedTime = new DateTimeOffset(DateTime.Now),
                Generator       = "Sandra.Snow Atom Generator"
            };

            feed.Authors.Add(new SyndicationPerson(authorEmail, author, siteUrl));

            var link = new SyndicationLink(new Uri(siteUrl + "/" + feedfileName))
            {
                RelationshipType = "self",
                MediaType        = "text/html",
                Title            = AtomTitle
            };

            feed.Links.Add(link);


            var formatter = new Atom10FeedFormatter(feed);

            return(stream =>
            {
                var encoding = new UTF8Encoding(false);
                var streamWrapper = new UnclosableStreamWrapper(stream);

                using (var writer = new XmlTextWriter(streamWrapper, encoding))
                {
                    formatter.WriteTo(writer);
                }
            });
        }
Exemplo n.º 9
0
        private bool RunPerResource(string resource)
        {
            bool logTargetResult = false;

            this.Logger.Write(string.Format("Starting synchronization for Resource {0} ", resource), Severity.Info);
            this.Logger.Write(string.Format("Source: {0}", this.SyncInfo.Source.GetResourceUri(resource)), Severity.Trace);
            this.Logger.Write(string.Format("Target: {0}", this.SyncInfo.Target.GetResourceUri(resource)), Severity.Trace);

            if ((this.SyncInfo.Logging != null) && (this.SyncInfo.Logging.Url != null))
            {
                this.Logger.Write(string.Format("Logging: {0}", this.SyncInfo.Logging.GetResourceUri(resource)), Severity.Trace);
                logTargetResult = true;
            }

            this.Logger.Write(string.Format("Direction: {0}", this.Direction.ToString()), Severity.Trace);


            HttpClient httpSourceClient       = null;
            Guid       sourceClientTrackingId = Guid.Empty;

            HttpClient httpTargetClient       = null;
            Guid       targetClientTrackingId = Guid.Empty;

            HttpClient httpLoggingClient = null;


            string tmpUrl;
            HttpResponseMessage respMsg;
            SyndicationFeed     tmpSourceFeed;
            SyndicationFeed     tmpTargetFeed;
            SyndicationLink     tmpSourceNextLink = null;
            SyndicationLink     tmpTargetNextLink = null;


            // Create application client objects
            if (Direction == SynchronisationDirection.forward)
            {
                httpSourceClient = GetHttpClient(SyncInfo.Source, SyncInfo.Proxy, resource);
                httpTargetClient = GetHttpClient(SyncInfo.Target, SyncInfo.Proxy, resource);
            }
            else
            {
                httpSourceClient = GetHttpClient(SyncInfo.Target, SyncInfo.Proxy, resource);
                httpTargetClient = GetHttpClient(SyncInfo.Source, SyncInfo.Proxy, resource);
            }

            if (logTargetResult)
            {
                httpLoggingClient = GetHttpClient(SyncInfo.Logging, SyncInfo.Proxy, resource);
                httpLoggingClient.TransportSettings.ConnectionTimeout = new TimeSpan(0, 5, 0);
            }


            // set timeout
            httpSourceClient.TransportSettings.ConnectionTimeout = new TimeSpan(0, 5, 0);
            httpTargetClient.TransportSettings.ConnectionTimeout = new TimeSpan(0, 5, 0);



            try
            {
                // *********************************************************
                // GET the sync digest from target applictaion ($syncDigest)
                // *********************************************************
                this.Logger.Write("Requesting the Sync Digest from target application.", Severity.Info);
                tmpUrl = GetSyncDigestGetUrl(resource);

                this.Logger.Write(string.Format("HTTP GET: {0}", tmpUrl), Severity.Trace);
                respMsg = httpTargetClient.Get(tmpUrl);
                this.Log(respMsg);

                // receive the content of the response
                respMsg.Content.LoadIntoBuffer();
                // handle errors
                this.ThrowIfNotStatusCode(HttpStatusCode.OK, respMsg);

                // check for correct content type of the result
                ThrowIfNoFeedEntry(respMsg);


                this.Logger.Write("Sync Digest received.", Severity.Info);

                // As we do not need to read the SyncDigest, the response content will be posted directly to the source application.
                // At the same time no reading means no validation. So eventually wrong data could be sent to the source application
                // with the next request. The source application must handle eventually wrong input data.


                // *************************************************************************
                // POST the retrieved Sync Digest to the source application ($syncSource)
                // *************************************************************************
                this.Logger.Write("Posting the Sync Digest from target application to the source application.", Severity.Info);
                sourceClientTrackingId = Guid.NewGuid();        // create the tracking ID for the asynchronous request
                tmpUrl = GetSyncSourcePostUrl(sourceClientTrackingId, resource);

                this.Logger.Write(string.Format("HTTP POST: {0}", tmpUrl), Severity.Trace);
                this.Logger.Write(string.Format("Content Type: {0}", ATOMFEEDENTRY), Severity.Trace);
                respMsg = httpSourceClient.Post(tmpUrl, ATOMFEEDENTRY, respMsg.Content);
                this.Log(respMsg);

                // receive the content of the response
                respMsg.Content.LoadIntoBuffer();
                // handle errors
                this.ThrowIfNotStatusCode(HttpStatusCode.Accepted, respMsg);

                // check for correct content type of the result
                ThrowIfNoXml(respMsg);

                // *************************************************************************
                // GET the Sync Feed from source application ($syncSource)
                // *************************************************************************
                // The helper method used here looks at the header of the response for the Location parameter
                // and requests the location url until a Status Code 200(OK) and an sdata feed is returned.
                // If an error occurred (No 200 or 202 status) an exception is thown.
                this.Logger.Write("Polling source application until retrieving sync feed.", Severity.Info);
                respMsg = this.RequestHeaderLocationUntilStatusIs200(respMsg, httpSourceClient);
                this.Log(respMsg);

                // check for correct content type of the result
                ThrowIfNoFeed(respMsg);

                // receive the content of the response
                respMsg.Content.LoadIntoBuffer();

                int sourceFeedPage = 1;
                do
                {
                    // parse source result as a feed
                    // needed to read a 'next' link, so that we can retrieve and submit the next page.
                    tmpSourceFeed = respMsg.Content.ReadAsSyndicationFeed();

                    Atom10FeedFormatter ff = tmpSourceFeed.GetAtom10Formatter();

                    // Handle error feed
                    this.ThrowIfDiagnosisFeed(tmpSourceFeed);

                    // *************************************************************************
                    // POST the retrieved Sync Feed to the target application ($syncTarget)
                    // *************************************************************************
                    this.Logger.Write(string.Format("Posting page {0} of the Sync Feed from source application to the target application.", sourceFeedPage), Severity.Info);
                    targetClientTrackingId = Guid.NewGuid();        // create the tracking ID for the asynchronous request
                    tmpUrl = GetSyncTargetPostUrl(targetClientTrackingId, resource);


                    this.Logger.Write(string.Format("HTTP POST: {0}", tmpUrl), Severity.Trace);
                    this.Logger.Write(string.Format("Content Type: {0}", ATOMFEED), Severity.Trace);
                    //XmlWriter writer;
                    //tmpSourceFeed.SaveAsAtom10(writer);


                    //HttpContent httpContent = HttpContent.Create(
                    respMsg = httpTargetClient.Post(tmpUrl, ATOMFEED, respMsg.Content);
                    this.Log(respMsg);

                    // receive the content of the response
                    respMsg.Content.LoadIntoBuffer();
                    // handle errors
                    this.ThrowIfNotStatusCode(HttpStatusCode.Accepted, respMsg);

                    // check for correct content type of the result
                    ThrowIfNoXml(respMsg);


                    // *************************************************************************
                    // GET the Sync Feed from target application ($syncTarget)
                    // *************************************************************************
                    // The helper method used here looks at the header of the response for the Location parameter
                    // and requests the location url until a Status Code 200(OK) and an sdata feed is returned.
                    // If an error occurred (No 200 or 202 status) an exception is thown.
                    this.Logger.Write("Polling target application until retrieving sync feed.", Severity.Info);
                    respMsg = this.RequestHeaderLocationUntilStatusIs200(respMsg, httpTargetClient);
                    this.Log(respMsg);

                    int targetFeedPage = 1;
                    do
                    {
                        // parse target result as a feed
                        // needed to read a 'next' link, so that we can retrieve and submit the next page.
                        tmpTargetFeed = respMsg.Content.ReadAsSyndicationFeed();

                        // Handle error feed
                        this.ThrowIfDiagnosisFeed(tmpTargetFeed);

                        // *************************************************************************
                        // POST the retrieved Sync Feed to the logging application ($syncResults)
                        // *************************************************************************
                        if (!logTargetResult)
                        {
                            this.Logger.Write("No logging url specified", Severity.Trace);
                        }
                        else
                        {
                            this.Logger.Write(string.Format("Posting page {0} of the Sync Feed from target application to the logging application.", targetFeedPage), Severity.Info);
                            tmpUrl = string.Format("{0}/{1}?runName={2}&runStamp={3}", SyncInfo.Logging.GetResourceUri(resource), "$syncResults", this.RunName, this.RunStamp.ToUniversalTime());

                            this.Logger.Write(string.Format("HTTP POST: {0}", tmpUrl), Severity.Trace);
                            this.Logger.Write(string.Format("Content Type: {0}", ATOMFEED), Severity.Trace);
                            respMsg = httpLoggingClient.Post(tmpUrl, ATOMFEED, respMsg.Content);
                            this.Log(respMsg);
                        }

                        // receive the content of the response
                        respMsg.Content.LoadIntoBuffer();
                        // handle errors
                        this.ThrowIfNotStatusCode(HttpStatusCode.OK, respMsg);

                        // *************************************************************************
                        // GET the next page of the Sync Feed of the target application($syncTarget)
                        // *************************************************************************
                        tmpTargetNextLink = tmpTargetFeed.GetNextPageLink();

                        if (null != tmpTargetNextLink)
                        {
                            // Todo: LOG
                            respMsg = httpTargetClient.Get(tmpTargetNextLink.Uri.ToString());
                            this.Log(respMsg);

                            // validate
                            respMsg.Content.LoadIntoBuffer();

                            targetFeedPage++;
                        }
                    } while (null != tmpTargetNextLink);


                    // *************************************************************************
                    // DELETE the batching context of the source application($syncSource)
                    // *************************************************************************
                    this.Logger.Write("Deleting batching context from target application.", Severity.Info);
                    tmpUrl = GetSyncTargetDeleteUrl(targetClientTrackingId, resource);

                    this.Logger.Write(string.Format("HTTP DELETE: {0}", tmpUrl), Severity.Trace);
                    respMsg = httpTargetClient.Delete(tmpUrl);
                    this.Log(respMsg);

                    // receive the content of the response
                    respMsg.Content.LoadIntoBuffer();
                    // handle errors
                    //this.ThrowIfNotStatusCode(HttpStatusCode.OK, respMsg);


                    // *************************************************************************
                    // GET the next page of the Sync Feed of the source application($syncSource)
                    // *************************************************************************
                    tmpSourceNextLink = tmpSourceFeed.GetNextPageLink();

                    if (null != tmpSourceNextLink)
                    {
                        // Todo: LOG
                        respMsg = httpSourceClient.Get(tmpSourceNextLink.Uri);
                        this.Log(respMsg);

                        // validate
                        respMsg.Content.LoadIntoBuffer();

                        sourceFeedPage++;
                    }
                } while (null != tmpSourceNextLink);


                // *************************************************************************
                // DELETE the batching context of the source application($syncSource)
                // *************************************************************************
                this.Logger.Write("Deleting batching context from source application.", Severity.Info);
                tmpUrl = GetSyncSourceDeleteUrl(sourceClientTrackingId, resource);

                this.Logger.Write(string.Format("HTTP DELETE: {0}", tmpUrl), Severity.Trace);
                respMsg = httpSourceClient.Delete(tmpUrl);
                this.Log(respMsg);

                // receive the content of the response
                respMsg.Content.LoadIntoBuffer();
                // handle errors
                //this.ThrowIfNotStatusCode(HttpStatusCode.OK, respMsg);

                this.Logger.Write("Synchronization succeeded.", Severity.Info);
            }
            catch (SdataException sdataException)
            {
                this.Logger.Write(sdataException.Diagnosis);
                return(false);
            }
            catch (Exception exception)
            {
                this.Logger.Write(exception);
                return(false);
            }
            return(true);
        }
Exemplo n.º 10
0
 public static AtomLink Link(this SyndicationLink link)
 {
     return(new AtomLink(link.Uri, link.RelationshipType, link.MediaType, link.Title));
 }
Exemplo n.º 11
0
        private void RssFeedForNews(HttpContext context)
        {
               context.Response.ContentType = "application/rss+xml";
  
        // Create the feed and specify the feed's attributes
        var myFeed = new SyndicationFeed
                         {
                             Title =
                                 SyndicationContent.CreatePlaintextContent(
                                     "admissionjankari.com- Education News - news"),
                             Description =
                                 SyndicationContent.CreatePlaintextContent(
                                     "admissionjankari.com- Education News - news"),
                             Copyright = SyndicationContent.CreatePlaintextContent("© " + DateTime.Now.Year.ToString(CultureInfo.InvariantCulture) + " Copyright | www.AdmissionJankari.com"),
                             Language = "en-us",
                             ImageUrl = new Uri(Utils.AbsoluteWebRoot + "image.axd?Common=logo.png")
                         };
        myFeed.Links.Add(new SyndicationLink(new Uri("http://www.admissionjankari.com/latest-news/"), "alternate", "Education-news", "text/html", 1000));
        myFeed.LastUpdatedTime = DateTimeOffset.Now;
           
        var feedItems = new List<SyndicationItem>();


        foreach (
            var newsList in
                NewsArticleNoticeProvider.Instance.GetLatestNews()
                                         .Where(result => result.NewsStatus)
                                         .ToList()
                                         .Take(10).OrderByDescending(result => result.NewsDate))
        {
          
            var item = new SyndicationItem
                           {
                               Title = SyndicationContent.CreatePlaintextContent(newsList.NewsSubject)
                           };
            item.Links.Add(
                SyndicationLink.CreateAlternateLink(
                    new Uri(
                            Utils.AbsoluteWebRoot +
                            ("news-details/" + Utils.RemoveIllegalCharacters(Convert.ToString(newsList.NewsSubject)))
                                .ToLower())));
            item.Summary = SyndicationContent.CreatePlaintextContent(newsList.NewsDesc);
           
            item.Categories.Add(new SyndicationCategory(newsList.NewsSubject));
            item.PublishDate = newsList.NewsDate;

        
            feedItems.Add(item);
        }

        myFeed.Items = feedItems;

        
        var outputSettings = new XmlWriterSettings
                                 {
                                     Indent = true
                                 };
            var feedWriter = XmlWriter.Create(context.Response.OutputStream, outputSettings);
      
            // Emit RSS 2.0
            var rssFormatter = new Rss20FeedFormatter(myFeed);
          
            rssFormatter.WriteTo(feedWriter);
    

        feedWriter.Close();
        }
        SyndicationFeed GetFeed()
        {
            #region -- Create Feed --
            SyndicationFeed feed = new SyndicationFeed();

            // set the feed ID to the main URL of your Website
            feed.Id = baseUrl;

            // set some properties on the feed
            feed.Title = new TextSyndicationContent("Блог VsyachePuz-а");
            /*feed.Description = new TextSyndicationContent("описание первого фида");*/
            //feed.Copyright = new TextSyndicationContent("Steve");
            feed.LastUpdatedTime = new DateTimeOffset(DateTime.Now);

            // since you are writing your own custom feed generator, you get to
            // name it!  Although this is not required.
            feed.Generator = "Руки";

            /*
             * // add your site or feed logo url
             * string imageUrl = baseUrl + "/images/mylogo.gif";
             * feed.ImageUrl = new Uri(imageUrl);
             */

            // Add the URL that will link to your published feed when it's done
            SyndicationLink link = new SyndicationLink(new Uri("https://raw.githubusercontent.com/VsyachePuz/blog/gh-pages/notifications/for-irc.atom"));
            link.RelationshipType = "self";
            link.MediaType        = "text/html";
            link.Title            = "VsyachePuz's blog feed";
            feed.Links.Add(link);

            // Add your site link
            link           = new SyndicationLink(new Uri(baseUrl));
            link.MediaType = "text/html";
            link.Title     = "Site link";
            feed.Links.Add(link);
            #endregion

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

            int maxArticles = 15;
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                var      it             = listView1.Items [i];
                Uri      urlOfArticle   = new Uri(GetColumnValue(it, "URL"));
                string   titleOfArticle = GetColumnValue(it, "Title");
                DateTime published      = DateTime.Parse(GetColumnValue(it, "Published"));
                DateTime updated        = DateTime.Parse(GetColumnValue(it, "Updated"));
                string   summary        = GetColumnValue(it, "Summary");

                // create new entry for feed
                SyndicationItem item = new SyndicationItem();

                // set the entry id to the URL for the item
                string url = urlOfArticle.AbsoluteUri;  // TODO: create the GetArticleUrl method
                item.Id = url;

                // Add the URL for the item as a link
                link = new SyndicationLink(urlOfArticle);
                item.Links.Add(link);

                // Fill some properties for the item
                item.Title           = new TextSyndicationContent(titleOfArticle);
                item.LastUpdatedTime = published;
                item.PublishDate     = updated;
                item.Summary         = new TextSyndicationContent(WebUtility.HtmlEncode(summary));

                /*
                 * // Fill the item content
                 * string html = String.Empty; // TODO: create the GetFeedEntryHtml method
                 * TextSyndicationContent content
                 * = new TextSyndicationContent(html, TextSyndicationContentKind.Html);
                 * item.Content = content;
                 */

                // Finally add this item to the item collection
                items.Add(item);

                // Stop after adding the max desired number of items
                if (items.Count >= maxArticles)
                {
                    break;
                }
            }

            feed.Items = items;
            return(feed);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Feed()
        {
            // Get posts
            var posts = await _context.Posts
                        .Include(q => q.User)
                        .Include(q => q.PostCategories).ThenInclude(q => q.Category)
                        .ToListAsync();

            // Create feed items
            var feedItems = new List <SyndicationItem>();

            foreach (var post in posts.Take(SiteSettings.FeedSize))
            {
                var feedItem = new SyndicationItem
                {
                    Title   = SyndicationContent.CreatePlaintextContent(post.Title),
                    Summary = SyndicationContent.CreatePlaintextContent(post.Summary),
                    Content = SyndicationContent.CreateHtmlContent(post.Content),
                    Authors = { new SyndicationPerson(post.User.Name) },
                    Links   =
                    {
                        SyndicationLink.CreateAlternateLink(new Uri(Url.Action("Post", "Blog", new
                        {
                            year  = post.DateCreated.Year,
                            month = post.DateCreated.Month,
                            slug  = post.Slug
                        },                                                             HttpContext.Request.Scheme)))
                    },
                    PublishDate = post.DateCreated
                };
                foreach (var postCategory in post.PostCategories)
                {
                    feedItem.Categories.Add(new SyndicationCategory(postCategory.Category.Name));
                }

                feedItems.Add(feedItem);
            }

            // Create feed
            var feed = new SyndicationFeed
            {
                Title       = SyndicationContent.CreatePlaintextContent(SiteSettings.Title),
                Description = SyndicationContent.CreatePlaintextContent(SiteSettings.Tagline),
                Links       = { SyndicationLink.CreateAlternateLink(new Uri(Url.Action("Index", "Blog", null, HttpContext.Request.Scheme))) },
                Items       = feedItems
            };

            // Serve the feed
            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/rss+xml; charset=utf-8"));
            }
        }
Exemplo n.º 14
0
 public static SyndicationLink FromDictionnary(Dictionary<string, object> link, string prefix = "")
 {
     if (link.ContainsKey("@" + prefix + "href")) {
         long length = 0;
         string rel = null;
         string title = null;
         string type = null;
         Uri href = new Uri((string)link["@" + prefix + "href"]);
         object r = null;
         if (link.TryGetValue("@" + prefix + "rel", out r))
             rel = (string)r;
         if (link.TryGetValue("@" + prefix + "title", out r))
             title = (string)r;
         if (link.TryGetValue("@" + prefix + "type", out r))
             type = (string)r;
         if (link.TryGetValue("@" + prefix + "", out r))
             if (r is string)
                 long.TryParse((string)r, out length);
             else
                 length = (long)r;
         SyndicationLink slink = new SyndicationLink(href, rel, title, type, length);
         return slink;
     }
     throw new ArgumentException("Not a link");
 }
Exemplo n.º 15
0
 public static void Snippet5()
 {
     // <Snippet5>
     SyndicationLink link = SyndicationLink.CreateAlternateLink(new Uri("http://server/link"), "text/html");
     // </Snippet5>
 }
Exemplo n.º 16
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());
            }
        }
Exemplo n.º 17
0
 public static void Snippet6()
 {
     // <Snippet6>
     SyndicationLink link = SyndicationLink.CreateMediaEnclosureLink(new Uri("http://server/link"), "audio/mpeg", 100000);
     // </Snippet6>
 }
Exemplo n.º 18
0
        public void NegativeLength()
        {
            SyndicationLink link = new SyndicationLink(new Uri("http://mono-project.com/index.rss"));

            link.Length = -1;
        }
Exemplo n.º 19
0
 public static void Snippet7()
 {
     // <Snippet7>
     SyndicationLink link = SyndicationLink.CreateSelfLink(new Uri("http://server/link"));
     // </Snippet7>
 }
Exemplo n.º 20
0
 public AtomResourceLink(SyndicationLink l)
 {
     this.atomLink = l;
 }
Exemplo n.º 21
0
 public static void Snippet8()
 {
     // <Snippet8>
     SyndicationLink link = SyndicationLink.CreateSelfLink(new Uri("http://server/link"), "text/html");
     // </Snippet8>
 }
Exemplo n.º 22
0
 public void CreateMediaEnclosureLink_NegativeLength_ThrowsArgumentOutOfRangeException()
 {
     AssertExtensions.Throws <ArgumentOutOfRangeException>("length", () => SyndicationLink.CreateMediaEnclosureLink(null, null, -1));
 }
Exemplo n.º 23
0
        /// <summary>Applies the information from a link to the specified resource.</summary>
        /// <param name='link'>LinkDescriptor with information to apply.</param>
        /// <param name="resourceSet">Set for the target resource.</param>
        /// <param name='resourceType'>Type for the target resource.</param>
        /// <param name='resource'>Target resource to which information will be applied.</param>
        /// <param name="propertyName">Name of the property that this link represents.</param>
        private void ApplyLink(SyndicationLink link, ResourceSetWrapper resourceSet, ResourceType resourceType, object resource, string propertyName)
        {
            Debug.Assert(link != null, "link != null");
            Debug.Assert(resourceType != null, "resourceType != null");
            Debug.Assert(resource != null, "resource != null");

            ResourceProperty property = resourceType.TryResolvePropertyName(propertyName);

            if (property == null)
            {
                // Open navigation properties are not supported on OpenTypes
                throw DataServiceException.CreateBadRequestError(Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(propertyName));
            }

            if (property.TypeKind != ResourceTypeKind.EntityType)
            {
                throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidNavigationPropertyName(propertyName, resourceType.FullName));
            }

            string      typeParameterValue = ValidateTypeParameterForNonOpenTypeProperties(link.MediaType, property);
            LinkContent linkContent        = this.HandleLinkContent(link, resource, resourceSet, resourceType, property, typeParameterValue, propertyName);

            #region Handle bind/unbind operation
            // If the href was specified empty or an empty inline element was specified, then we will set the
            // reference to null - this helps in overrriding if there was a default non-value for this property
            // else if only link element was specified, and then href points to a single result, then we will
            // perform a bind operation
            if ((linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && String.IsNullOrEmpty(link.Uri.OriginalString)) ||
                linkContent == LinkContent.EmptyInlineElementSpecified)
            {
                // update the object count when you are performing a bind operation
                this.CheckAndIncrementObjectCount();
                if (property != null && property.Kind == ResourcePropertyKind.ResourceSetReference)
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_CannotSetCollectionsToNull(propertyName));
                }

                // For open properties, we will assume that this is a reference property and set it to null
                this.Updatable.SetReference(resource, propertyName, null);
            }
            else if (linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && !String.IsNullOrEmpty(link.Uri.OriginalString))
            {
                // update the object count when you are performing a bind operation
                this.CheckAndIncrementObjectCount();

                // If the link points to a reference navigation property, then update the link
                Uri referencedUri = RequestUriProcessor.GetAbsoluteUriFromReference(link.Uri.OriginalString, this.Service.OperationContext);
                RequestDescription description = RequestUriProcessor.ProcessRequestUri(referencedUri, this.Service);
                if (!description.IsSingleResult)
                {
                    if (property != null && property.Kind == ResourcePropertyKind.ResourceReference)
                    {
                        throw DataServiceException.CreateBadRequestError(Strings.BadRequest_LinkHrefMustReferToSingleResource(propertyName));
                    }

                    return;
                }

                // no need to check for null. For collection properties, they can never be null and that
                // check has been added below. For reference properties, if they are null, it means unbind
                // and hence no need to check for null.
                // Get the resource
                object targetResource = this.Service.GetResource(description, description.SegmentInfos.Length - 1, null);
                if (property.Kind == ResourcePropertyKind.ResourceReference)
                {
                    this.Updatable.SetReference(resource, propertyName, targetResource);
                }
                else
                {
                    WebUtil.CheckResourceExists(targetResource != null, description.LastSegmentInfo.Identifier);
                    this.Updatable.AddReferenceToCollection(resource, propertyName, targetResource);
                }
            }
            #endregion Handle bind/unbind operation
        }
Exemplo n.º 24
0
 public SyndicationLinkSubclass(SyndicationLink source) : base(source)
 {
 }
Exemplo n.º 25
0
        /// <summary>
        /// Handle the contents under the link element
        /// </summary>
        /// <param name="link">syndication link element</param>
        /// <param name="parentResource">parent resource which contains the link.</param>
        /// <param name="parentResourceSet">resource set of the parent resource</param>
        /// <param name="parentResourceType">resource type of the parent resource</param>
        /// <param name="property">property representing the link.</param>
        /// <param name="typeParameterValue">type parameter value as specified in the type attribute.</param>
        /// <param name="propertyName">name of the property that this link represents.</param>
        /// <returns>returns whether there are child elements under link element.</returns>
        private LinkContent HandleLinkContent(
            SyndicationLink link,
            object parentResource,
            ResourceSetWrapper parentResourceSet,
            ResourceType parentResourceType,
            ResourceProperty property,
            string typeParameterValue,
            string propertyName)
        {
            Debug.Assert(parentResource != null, "parent resource cannot be null");
            Debug.Assert(property != null, "property != null");
            Debug.Assert(link != null, "link != null");

            LinkContent linkContent = LinkContent.NoInlineElementSpecified;

            foreach (var e in link.ElementExtensions)
            {
                // link can contain other elements apart from the inline elements.
                if (e.OuterNamespace != XmlConstants.DataWebMetadataNamespace ||
                    e.OuterName != XmlConstants.AtomInlineElementName)
                {
                    continue;
                }

                // Deep payload cannot be specified for update
                if (this.Update)
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_DeepUpdateNotSupported);
                }

                linkContent = LinkContent.EmptyInlineElementSpecified;
                using (XmlReader linkReader = e.GetReader())
                {
                    while (linkReader.Read())
                    {
                        if (linkReader.NodeType == XmlNodeType.Element)
                        {
                            string elementName  = linkReader.LocalName;
                            string namespaceUri = linkReader.NamespaceURI;
                            if (namespaceUri != XmlConstants.AtomNamespace)
                            {
                                throw DataServiceException.CreateBadRequestError(
                                          Strings.BadRequest_InlineElementMustContainValidElement(
                                              elementName,
                                              XmlConstants.AtomInlineElementName,
                                              XmlConstants.AtomFeedElementName,
                                              XmlConstants.AtomEntryElementName));
                            }

                            ResourceSetWrapper targetSet = this.Service.Provider.GetContainer(parentResourceSet, parentResourceType, property);
                            if (targetSet == null)
                            {
                                throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidPropertyNameSpecified(propertyName, parentResourceType.FullName));
                            }

                            // FeatureVersion needs to be 2.0 if any of the property in the types contained in the resource set has KeepInContent false
                            this.RequestDescription.UpdateAndCheckEpmFeatureVersion(targetSet, this.Service);

                            linkContent = LinkContent.InlineElementContainsData;
                            if (elementName == XmlConstants.AtomEntryElementName)
                            {
                                if (property.Kind != ResourcePropertyKind.ResourceReference)
                                {
                                    throw DataServiceException.CreateBadRequestError(Strings.Syndication_EntryElementForReferenceProperties(e.OuterName, propertyName));
                                }

                                // Make sure if the media type is specified. If its specified, it should better be link
                                SyndicationItem propertyItem;
                                propertyItem = ReadSyndicationItem(this.factory.CreateSyndicationItemFormatter(), linkReader);

                                SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, true /* singleResult */);
                                Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes.");

                                object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, propertyItem);
                                this.Updatable.SetReference(parentResource, propertyName, propertyValue);
                            }
                            else if (elementName == XmlConstants.AtomFeedElementName)
                            {
                                if (property.Kind != ResourcePropertyKind.ResourceSetReference)
                                {
                                    throw DataServiceException.CreateBadRequestError(Strings.Syndication_FeedElementForCollections(e.OuterName, propertyName));
                                }

                                SyndicationFeed propertyFeed;
                                propertyFeed = ReadSyndicationFeed(this.factory.CreateSyndicationFeedFormatter(), linkReader);

                                SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, false /* singleResult */);
                                Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes.");

                                foreach (SyndicationItem item in propertyFeed.Items)
                                {
                                    object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, item);
                                    if (propertyValue == null)
                                    {
                                        if (propertySegment.ProjectedProperty != null &&
                                            propertySegment.ProjectedProperty.Kind == ResourcePropertyKind.ResourceSetReference)
                                        {
                                            throw DataServiceException.CreateBadRequestError(
                                                      Strings.BadRequest_CannotSetCollectionsToNull(propertyName));
                                        }
                                    }

                                    Debug.Assert(
                                        propertySegment.TargetSource == RequestTargetSource.Property &&
                                        propertySegment.TargetKind == RequestTargetKind.Resource &&
                                        propertySegment.SingleResult == false,
                                        "Must be navigation set property.");

                                    this.Updatable.AddReferenceToCollection(parentResource, propertyName, propertyValue);
                                }
                            }
                            else
                            {
                                throw DataServiceException.CreateBadRequestError(
                                          Strings.BadRequest_InlineElementMustContainValidElement(
                                              elementName,
                                              XmlConstants.AtomInlineElementName,
                                              XmlConstants.AtomFeedElementName,
                                              XmlConstants.AtomEntryElementName));
                            }
                        }
                    }
                }
            }

            return(linkContent);
        }
Exemplo n.º 26
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();
        }
        private void GenerateFeed()
        {
            CertificateTableAdapter certificateAdapter = new CertificateTableAdapter();


            String description = "";

            String siteUrl     = "http://" + EnvDomain;
            String homePageUrl = siteUrl + ResolveUrl("~/Default.aspx") + "?station_id=" + StationId;

            //mainFeed.Title = TextSyndicationContent.CreatePlaintextContent(Station.SiteNamePlainText);
            //mainFeed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(homePageUrl)));


            List <DollarSaverDB.CertificateRow> listCertificates = new List <DollarSaverDB.CertificateRow>();

            if (Station.StationSiteType == SiteType.Standard)
            {
                SpecialSettingsTableAdapter            specialSettingsAdapter = new SpecialSettingsTableAdapter();
                DollarSaverDB.SpecialSettingsDataTable specialSettingsTable   = specialSettingsAdapter.GetSpecialSettings(StationId);

                bool dailyHeader = false;
                if (specialSettingsTable.Count == 1)
                {
                    dailyHeader = specialSettingsTable[0].DailyHeader;
                }

                if (dailyHeader)
                {
                    description = "Daily Deal";
                }
                else
                {
                    description = "Weekly Deal";
                }

                DollarSaverDB.CertificateDataTable daily = certificateAdapter.GetSpecial(StationId, 1);
                if (daily.Count == 1)
                {
                    listCertificates.Add(daily[0]);
                }
            }
            else
            {
                description = "Deal of the Week";

                DollarSaverDB.CertificateDataTable certificateTable = certificateAdapter.GetCurrentDeal(StationId);

                if (certificateTable.Count == 1)
                {
                    listCertificates.Add(certificateTable[0]);
                }
            }

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

            foreach (DollarSaverDB.CertificateRow certificate in listCertificates)
            {
                SyndicationItem item = new SyndicationItem();

                item.Title = TextSyndicationContent.CreatePlaintextContent(certificate.AdvertiserName);

                String advertiserUrl = siteUrl + ResolveUrl("~/Advertiser.aspx?advertiser_id=" + certificate.AdvertiserId);

                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(advertiserUrl)));


                StringBuilder content = new StringBuilder();


                if (certificate.Advertiser.LogoUrl != String.Empty)
                {
                    String logoUrl = siteUrl + ResolveUrl(certificate.Advertiser.LogoUrl);

                    int logoWidth  = 125;
                    int logoHeight = 75;

                    if (certificate.Advertiser.IsLogoImageVertical)
                    {
                        logoWidth  = 75;
                        logoHeight = 125;
                    }

                    content.Append("<div>");
                    content.Append("<a href=\"" + advertiserUrl + "\">");
                    content.Append("<img src=\"" + logoUrl + "\"  alt=\"" + Server.HtmlEncode(certificate.AdvertiserName) + "\" style=\"border-color:#404040;border-width:1px;border-style:solid;height:" + logoHeight + "px;width:" + logoWidth + "px;\">");
                    content.Append("</a>");
                    content.Append("</div>");
                }

                content.Append("<div style=\"font-family: Arial;\">");

                //content.Append("<a href=\"" + advertiserUrl + "\" style=\"font-weight: bold; font-size: 1.3em; line-height: 1.7em;\">" + Server.HtmlEncode(certificate.AdvertiserName) + "</a>");

                content.Append("<p>");
                content.Append(certificate.Advertiser.Description);
                content.Append("</p>");
                content.Append("<a href=\"" + advertiserUrl + "\" style=\"font-weight: bold; font-size: 1.1em; line-height: 1.5em;\">" + Server.HtmlEncode(certificate.ShortName) + "<a>");
                content.Append("<p> ");
                content.Append(certificate.Description);
                content.Append("</p>");
                content.Append("<p style=\"font-weight: bold;\"> ");
                content.Append("Certificate Value: " + certificate.FaceValue.ToString("$0.00") + "<br />");
                content.Append("Price: <span style=\"color: red;\">" + certificate.DiscountValue.ToString("$0.00") + "</span><br />");
                content.Append("Your Savings: " + certificate.Savings + "<br />");
                content.Append("</p>");
                content.Append("<a href=\"" + advertiserUrl + "\" style=\"font-weight: bold; font-size: 1.1em; line-height: 1.5em;\">BUY NOW</a>");
                content.Append("</div>");
                content.Append("<div style=\"clear: both;\"></div>");


                item.Content = SyndicationContent.CreateHtmlContent(content.ToString());

                items.Add(item);
            }


            SyndicationFeed mainFeed = new SyndicationFeed(Station.SiteNamePlainText, description, new Uri(homePageUrl));

            mainFeed.Description = TextSyndicationContent.CreatePlaintextContent(description);

            mainFeed.Items = items;

            Response.ContentType = "application/rss+xml";

            using (XmlWriter xmlWriter = XmlWriter.Create(Response.OutputStream)) {
                Rss20FeedFormatter rssFeed = new Rss20FeedFormatter(mainFeed);
                rssFeed.WriteTo(xmlWriter);
            }
        }
Exemplo n.º 28
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>();

            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);
        }
Exemplo n.º 29
0
        public Atom10FeedFormatter GetFragmentsFeed(string collectionId, DateTime since, DateTime before, int page = 1)
        {
            Logging.LogInfo("GetFragments Feed {0} {1}", page, since);
            var collectionProvider = ConfigurationReader.Configuration.CollectionProviders.Where(cp => cp.Name.Equals(collectionId)).FirstOrDefault();

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

            const int pageSize = 1000;

            IList <SyndicationItem> feedItems = new List <SyndicationItem>();
            IEnumerable <IFragment> fragments = collectionProvider.GetFragments(since, before);

            var skip            = (page - 1) * pageSize;
            var fragmentWritten = false;

            foreach (var fragment in fragments.Skip(skip).Take(pageSize))
            {
                fragmentWritten = true;

                // create snapshot item
                var fragmentUri = new Uri("fragment?id=" + fragment.ResourceId, UriKind.Relative);

                var item = new SyndicationItem
                {
                    Title           = new TextSyndicationContent(fragment.ResourceName),
                    Id              = fragmentUri.ToString(),
                    LastUpdatedTime = fragment.PublishDate
                };

                var sl = new SyndicationLink(new Uri(fragmentUri + "&format=xml", UriKind.Relative))
                {
                    RelationshipType = "http://www.sdshare.org/2012/core/fragment",
                    MediaType        = "application/rdf+xml"
                };
                item.Links.Add(sl);

                sl = new SyndicationLink(new Uri(fragmentUri + "&format=xml", UriKind.Relative))
                {
                    RelationshipType = "alternate",
                    MediaType        = "application/rdf+xml"
                };
                item.Links.Add(sl);

                item.ElementExtensions.Add("TopicSI", "http://www.egovpt.org/sdshare", fragment.ResourceUri);
                item.ElementExtensions.Add("ResourceUri", SdShareNamespace, fragment.ResourceUri);
                feedItems.Add(item);
            }

            var feed = new SyndicationFeed(feedItems)
            {
                Title           = new TextSyndicationContent(collectionId + " Fragments"),
                LastUpdatedTime = DateTime.UtcNow
            };

            // make feed paging links
            var firstPageLink = new SyndicationLink(new Uri("fragments?page=1", UriKind.Relative))
            {
                RelationshipType = "first",
                MediaType        = "application/atom+xml"
            };

            feed.Links.Add(firstPageLink);

            if (fragmentWritten)
            {
                var nextPageLink = new SyndicationLink(new Uri("fragments?page=" + (page + 1), UriKind.Relative))
                {
                    RelationshipType = "next",
                    MediaType        = "application/atom+xml"
                };
                feed.Links.Add(nextPageLink);
            }

            if (page > 1)
            {
                var prevPageLink = new SyndicationLink(new Uri("fragments?page=" + (page - 1), UriKind.Relative))
                {
                    RelationshipType = "prev",
                    MediaType        = "application/atom+xml"
                };
                feed.Links.Add(prevPageLink);
            }

            return(new Atom10FeedFormatter(feed));
        }
Exemplo n.º 30
0
 public static SyndicationLink FromJTokenList(JToken link, string prefix = "")
 {
     if (link.SelectToken("@" + prefix + "href") != null) {
         long length = 0;
         string rel = null;
         string title = null;
         string type = null;
         Uri href = new Uri((string)link.SelectToken("@" + prefix + "href").ToString());
         object r = null;
         if (link.SelectToken("@" + prefix + "rel") != null)
             rel = link.SelectToken("@" + prefix + "rel").ToString();
         if (link.SelectToken("@" + prefix + "title") != null)
             title = link.SelectToken("@" + prefix + "title").ToString();
         if (link.SelectToken("@" + prefix + "type") != null)
             type = link.SelectToken("@" + prefix + "type").ToString();
         if (link.SelectToken("@" + prefix + "size") != null)
             long.TryParse(link.SelectToken("@" + prefix + "size").ToString(), out length);
         else
             length = 0;
         SyndicationLink slink = new SyndicationLink(href, rel, title, type, length);
         return slink;
     }
     throw new ArgumentException("Not a link");
 }
Exemplo n.º 31
0
        public Atom10FeedFormatter GetCollectionFeed(string collectionId)
        {
            var collectionProvider = ConfigurationReader.Configuration.CollectionProviders.Where(cp => cp.Name.Equals(collectionId)).FirstOrDefault();

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

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

            // create snapshotfeed link
            var item = new SyndicationItem
            {
                Title           = new TextSyndicationContent("Snapshot feed for " + collectionId),
                Id              = Guid.NewGuid().ToString(),
                LastUpdatedTime = DateTime.UtcNow
            };

            var sl = new SyndicationLink(new Uri(collectionId + "/snapshots", UriKind.Relative))
            {
                RelationshipType = SdShareNamespace + "snapshotsfeed",
                MediaType        = "application/atom+xml"
            };

            item.Links.Add(sl);
            item.Links.Add(new SyndicationLink(new Uri(collectionId + "/snapshots", UriKind.Relative))
            {
                RelationshipType = "alternate", MediaType = "application/atom+xml"
            });
            feedItems.Add(item);

            // create fragments link
            item = new SyndicationItem
            {
                Title           = new TextSyndicationContent("Fragments feed for " + collectionId),
                Id              = Guid.NewGuid().ToString(),
                LastUpdatedTime = DateTime.UtcNow
            };

            var fl = new SyndicationLink(new Uri(collectionId + "/fragments", UriKind.Relative))
            {
                RelationshipType = SdShareNamespace + "fragmentsfeed",
                MediaType        = "application/atom+xml"
            };

            item.Links.Add(fl);
            item.Links.Add(new SyndicationLink(new Uri(collectionId + "/fragments", UriKind.Relative))
            {
                RelationshipType = "alternate", MediaType = "application/atom+xml"
            });
            feedItems.Add(item);

            var feed = new SyndicationFeed(feedItems)
            {
                Title           = new TextSyndicationContent(collectionId + " Feed"),
                LastUpdatedTime = DateTime.UtcNow
            };

            return(new Atom10FeedFormatter(feed));
        }
        internal static SyndicationLink SyndicationLinkFromXElement(XElement elem) {

            var atom = XNamespace.Get("http://www.w3.org/2005/Atom");

            SyndicationLink link = new SyndicationLink(new Uri(elem.Attribute(atom + "href").Value));
            if (elem.Attribute(atom + "rel") != null)
                link.RelationshipType = elem.Attribute(atom + "rel").Value;
            if (elem.Attribute(atom + "title") != null)
                link.Title = elem.Attribute(atom + "title").Value;
            if (elem.Attribute(atom + "type") != null)
                link.MediaType = elem.Attribute(atom + "type").Value;
            if (elem.Attribute(atom + "length") != null)
                link.Length = long.Parse(elem.Attribute(atom + "length").Value);
            return link;

        }
Exemplo n.º 33
0
        public FileResult Index(string path, bool recursive = false, string title = null)
        {
            path = ValidatePath(path);

            var baseDirInfo = new DirectoryInfo(path);

            var feed = new SyndicationFeed(
                title ?? baseDirInfo.Name,
                $"{(recursive ? "Recursive " : "")}Filefeed generated feed for {baseDirInfo.FullName}",
                new Uri($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}")
                );

            var folderImage = baseDirInfo.GetFiles("folder.*").FirstOrDefault();

            if (folderImage != null)
            {
                feed.ImageUrl = new Uri($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}" + Url.Action("GetFile", new { Path = folderImage.FullName }));
            }

            var files = baseDirInfo.EnumerateFiles(
                "*",
                new EnumerationOptions {
                RecurseSubdirectories = recursive
            })
                        .Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden) && !x.Name.ToLower().StartsWith("folder."))
                        .Take(100)
                        .OrderBy(x => x.FullName);

            var items = new List <SyndicationItem>(files.Count());

            //We fake the date to get a publish date in the same order as alphabetical
            var pubDate = new DateTime(DateTime.Now.Year - 1, 1, 1, 12, 0, 0);

            foreach (var file in files)
            {
                if (!_contentTypeProvider.TryGetContentType(file.Name, out var type))
                {
                    type = System.Net.Mime.MediaTypeNames.Application.Octet;
                }

                var item = new SyndicationItem
                {
                    Title       = new TextSyndicationContent(file.Name),
                    Id          = Url.Action("GetFile", new { Path = file.FullName }),
                    PublishDate = pubDate,
                };
                item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(
                                   new Uri($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}" + Url.Action("GetFile", new { Path = file.FullName })),
                                   type,
                                   file.Length));
                pubDate = pubDate.AddDays(1);

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

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

            Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);

            rssFormatter.SerializeExtensionsAsAtom = false;
            using (var stream = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(stream, settings))
                {
                    rssFormatter.WriteTo(writer);
                    writer.Flush();
                    return(File(stream.ToArray(), "application/rss+xml; charset=utf-8"));
                }
            }
        }