Example #1
0
        public ActionResult AndroidRivers()
        {
            var feed = new SyndicationFeed();
            feed.Language = "en";
            feed.Description = new TextSyndicationContent("This is the update feed for Android Rivers", TextSyndicationContentKind.Plaintext);
            feed.Title = new TextSyndicationContent("Android Rivers Update Feed", TextSyndicationContentKind.Plaintext);
            feed.Items = new SyndicationItem[]{
                Update("Android Rivers 1.02 released", 102,
                @"
            - Fix sorting issue that is case insensitive
                 ",
                  new DateTime(2013, 1, 20).ToUniversalTime(),
                  new Uri("http://goo.gl/Vo2bx"))
            };

            feed.AttributeExtensions.Add(new XmlQualifiedName("mobileapp", XNamespace.Xmlns.ToString()), RSS_SOFTWARE_UPDATES_EXTENSION);

            var rssOutput = new StringBuilder();
            using (var xml = XmlWriter.Create(rssOutput))
            {
                feed.SaveAsRss20(xml);
            }

            //Read http://baleinoid.com/whaly/2009/07/xmlwriter-and-utf-8-encoding-without-signature/
            var payload = rssOutput.ToString().Replace("encoding=\"utf-16\"", ""); //remove the Processing Instruction encoding mark for the xml body = it's a hack I know
            return Content(payload, "application/rss+xml");
        }
        public static string GetSyndicationFeed(this IEnumerable<Notification> notifications, string contentType)
        {
            var feed = new SyndicationFeed("System notification", "Publishes system notifications", new Uri("http://localhost"));
            feed.Authors.Add(new SyndicationPerson("[email protected]", "Testor Testorsson", "http://localhost"));
            feed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(HttpContext.Current.Request.Url.AbsoluteUri), "application/atom+xml"));
            feed.Items = notifications.ASyndicationItems(feed);

            var stringWriter = new StringWriter();

            XmlWriter feedWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings
            {
                OmitXmlDeclaration = true
            });

            feed.Copyright = SyndicationContent.CreatePlaintextContent("Copyright hygia");
            feed.Language = "en-us";

            if (contentType == ContentTypes.Atom)
                feed.SaveAsAtom10(feedWriter);
            else
                feed.SaveAsRss20(feedWriter);

            feedWriter.Close();

            return stringWriter.ToString();
        }
Example #3
0
        public void ProcessRequest(HttpContext context)
        {
            var packageName = context.Request.QueryString["packageId"];

            var nugetContext = new Nuget.GalleryFeedContext(new Uri(NugetServiceUri));
            var last = (from x in nugetContext.Packages where x.Id == packageName && x.IsLatestVersion select new { x.DownloadCount, x.Version }).First();

            var items = GetSyndicationItems(packageName, last.DownloadCount);
            var nugetUrl = string.Format(
                "{0}/Packages(Id='{1}',Version='{2}')", NugetServiceUri, packageName, last.Version);

            var feed = new SyndicationFeed("Nuget Download Count Feed",
                                           "Provides the current total download count for a Nuget Package",
                                           new Uri(nugetUrl), nugetUrl, items.Last().LastUpdatedTime,
                                           items);
            using (var xmlWriter = XmlWriter.Create(context.Response.OutputStream))
            {
                feed.SaveAsRss20(xmlWriter);
                xmlWriter.Flush();
                xmlWriter.Close();
            }

            context.Response.ContentType = "text/xml";
            context.Response.End();
        }
 private static string WriteFeedToRssString(SyndicationFeed feed)
 {
     StringBuilder stringBuilder = new StringBuilder();
     XmlWriter xmlWriter = XmlWriter.Create(stringBuilder);
     feed.SaveAsRss20(xmlWriter);
     xmlWriter.Flush();
     return stringBuilder.ToString();
 }
    private async Task DownloadFeeds()
    {
        var rss = new SyndicationFeed(config.AppSettings["title"], config.AppSettings["description"], null);

        foreach (var key in config.AppSettings.AllKeys.Where(key => key.StartsWith("feed:")))
        {
            SyndicationFeed feed = await DownloadFeed(config.AppSettings[key]);
            rss.Items = rss.Items.Union(feed.Items).GroupBy(i => i.Title.Text).Select(i => i.First()).OrderByDescending(i => i.PublishDate.Date);
        }

        using (XmlWriter writer = XmlWriter.Create(_masterFile))
            rss.SaveAsRss20(writer);

        using (XmlWriter writer = XmlWriter.Create(_feedFile))
        {
            rss.Items = rss.Items.Take(10);
            rss.SaveAsRss20(writer);
        }
    }
Example #6
0
        public ActionResult Search(string terms, string source, string locale, int index = 1, int size = 20, string format = "")
        {
            //App.Get().SetCulture(locale);
            var src = string.IsNullOrEmpty(source) ? App.Get().Searcher.Sources.First().Name : source;
            if (terms == null)
            {
                ViewBag.Query = new SearchQuery()
                {
                    Source = src,
                    Locale = locale
                };
                return View();
            }

            var searchQuery = new SearchQuery()
            {
                Index = index - 1,
                Size = size,
                Source = src,
                Terms = terms,
                Locale = locale
            };

            var model = App.Get().Searcher.Search(searchQuery);
            var feed = new SyndicationFeed(string.Format("Search for {0}", terms), src, Request.Url, model);
            feed.Generator = "DotNetAge";

            if (format.Equals("rss", System.StringComparison.OrdinalIgnoreCase) ||
                format.Equals("atom", System.StringComparison.OrdinalIgnoreCase))
            {
                var sb = new StringBuilder();
                using (var writer = System.Xml.XmlWriter.Create(sb))
                {
                    if (format.Equals("rss", System.StringComparison.OrdinalIgnoreCase))
                    {
                        feed.SaveAsRss20(writer);
                        writer.Flush();
                        return Content(sb.ToString(), "text/xml", Encoding.UTF8);
                    }

                    if (format.Equals("atom", System.StringComparison.OrdinalIgnoreCase))
                    {
                        feed.SaveAsAtom10(writer);
                        writer.Flush();
                        return Content(sb.ToString(), "text/xml", Encoding.UTF8);
                    }
                }
            }
            ViewBag.Query = searchQuery;

            return Json(feed,JsonRequestBehavior.AllowGet);
        }
    private async Task DownloadFeeds()
    {
        var rss = new SyndicationFeed("Programmer Feeds", "Personal Feeds", null);
        string jsonFeed = File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath(Constants.DATA_FEED));
        var feeds = JsonConvert.DeserializeObject<List<Feeds>>(jsonFeed);

        foreach (var f in feeds)
        {
            SyndicationFeed feed = await DownloadFeed(f.feedurl);
            rss.Items = rss.Items.Union(feed.Items).GroupBy(i => i.Title.Text).Select(i => i.First()).OrderByDescending(i => i.PublishDate.Date);
        }

        using (XmlWriter writer = XmlWriter.Create(_masterFile))
        {
            rss.SaveAsRss20(writer);
        }

        using (XmlWriter writer = XmlWriter.Create(_feedFile))
        {
            rss.Items = rss.Items.Take(10);
            rss.SaveAsRss20(writer);
        }
    }
Example #8
0
        public ActionResult Feed(string format)
        {
            var posts = _index.GetBlogPosts().OrderByDescending(x => x.PostedAt);

            // Create feed items.
            var items = new List<SyndicationItem>();
            foreach (var post in posts)
            {
                var feedItem = new SyndicationItem
                {
                    Content = new TextSyndicationContent(post.FeedBody, TextSyndicationContentKind.Html),
                    Id = post.Id,
                    PublishDate = post.PostedAt,
                    Title = new TextSyndicationContent(post.Title, TextSyndicationContentKind.Plaintext),
                };

                var url = string.Concat("http://cakebuild.net", LinkHelper.GetLink(post));
                feedItem.Links.Add(new SyndicationLink(new Uri(url)));
                items.Add(feedItem);
            }

            // Create the feed.
            var feed = new SyndicationFeed(items)
            {
                Title = new TextSyndicationContent("Cake", TextSyndicationContentKind.Plaintext),
                Description = new TextSyndicationContent("The Cake blog feed", TextSyndicationContentKind.Plaintext)
            };

            // Write the feed as a response.
            // TODO: Cache this at start up?
            using (var ms = new MemoryStream())
            {
                var writer = XmlWriter.Create(ms);

                var contentType = "application/atom+xml";
                if (string.Equals("rss", format, StringComparison.InvariantCultureIgnoreCase))
                {
                    feed.SaveAsRss20(writer);
                    contentType = "application/rss+xml";
                }
                else
                {
                    feed.SaveAsAtom10(writer);
                }

                writer.Flush();
                var text = Encoding.UTF8.GetString(ms.ToArray());
                return Content(text, contentType, Encoding.UTF8);
            }
        }
        private static async Task MainAsync(string[] args)
        {
            var feedTitle = ConfigurationManager.AppSettings["FeedTitle"];
            var description = ConfigurationManager.AppSettings["FeedDescription"];
            var folderItemId = ConfigurationManager.AppSettings["OneDrive:FolderItemId"];

            string path = await GetOneDriveFolderPathAsync(folderItemId);

            var directoryPath = args.Length > 0 ? args[0] : ".";
            var di = new DirectoryInfo(directoryPath);
            var syndicationItems = di
                .EnumerateFiles("*.mp3")
                .OrderByDescending(f => f.CreationTime)
                .Select(file => GetSyndicationItem(path, file));
            var feed = new SyndicationFeed(feedTitle, description, GetOneDriveFileUrl(path, RssXml), syndicationItems);

            using (var textWriter = new XmlTextWriter(Path.Combine(directoryPath, RssXml), Encoding.UTF8))
            {
                feed.SaveAsRss20(textWriter);
            }
        }
Example #10
0
        public void Execute()
        {
            //
            // RSSを作成には以下の手順で構築する.
            //
            // (1) SyndicationItemを作成し、リストに追加
            // (2) SyndicationFeedを作成し、(1)で作成したリストを追加
            // (3) XmlWriterを構築し、出力.
            //
            var items = new List<SyndicationItem>();

            for (var i = 0; i < 10; i++)
            {
                var newItem = new SyndicationItem();

                newItem.Title = new TextSyndicationContent($"Test Title-{i}");
                newItem.Links.Add(new SyndicationLink(new Uri(@"http://www.google.co.jp/")));

                items.Add(newItem);
            }

            var feed = new SyndicationFeed("Test Feed", "This is a test feed", new Uri(@"http://www.yahoo.co.jp/"), items);
            feed.LastUpdatedTime = DateTime.Now;

            var sb = new StringBuilder();
            var settings = new XmlWriterSettings();
            settings.Indent = true;

            using (var writer = XmlWriter.Create(sb, settings))
            {
                //feed.SaveAsAtom10(writer);
                feed.SaveAsRss20(writer);
                writer.Close();
            }

            Output.WriteLine(sb.ToString());
        }
Example #11
0
        public static Stream GetServiceStream(string format, string callback, DataTable dt, SyndicationFeed sf)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            if (format == "xml")
            {
                XmlSerializer xmls = new XmlSerializer(typeof(DataTable));
                xmls.Serialize(writer, dt);
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
            }
            else if (format == "json")
            {
                var toJSON = new JavaScriptSerializer();
                toJSON.RegisterConverters(new JavaScriptConverter[] { new JavaScriptDataTableConverter() });
                writer.Write(toJSON.Serialize(dt));
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/json";
            }
            else if (format == "jsonp")
            {
                var toJSON = new JavaScriptSerializer();
                toJSON.RegisterConverters(new JavaScriptConverter[] { new JavaScriptDataTableConverter() });
                writer.Write(callback + "( " + toJSON.Serialize(dt) + " );");
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/json";
            }
            else if (format == "rss")
            {
                XmlWriter xmlw = new XmlTextWriter(writer);
                sf.SaveAsRss20(xmlw);
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
            }
            else if (format == "atom")
            {
                XmlWriter xmlw = new XmlTextWriter(writer);
                sf.SaveAsAtom10(xmlw);
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
            }
            else if (format == "help")
            {
                StreamReader sr = new StreamReader(ConfigurationManager.AppSettings["ServiceDocumentation"].ToString());
                writer.Write(sr.ReadToEnd());
                sr.Close();
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
            }
            else
            {
                writer.Write("Invalid formatting specified.");
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
            }

            writer.Flush();
            stream.Position = 0;
            return stream;
        }
Example #12
0
        /// <summary>
        /// Takes a syndication feed and returns an RSS string
        /// </summary>
        /// <param name="feed">Syndication Feed</param>
        /// <returns>RSS formated string</returns>
        public static string SerializeToRss(SyndicationFeed feed)
        {
            using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = new UTF8Encoding(false);
                //settings.Indent = true;

                using (XmlWriter xWriter = XmlWriter.Create(writer, settings))
                {
                    feed.SaveAsRss20(xWriter);
                    xWriter.Flush();
                    return writer.ToString();
                }
            }
        }
Example #13
0
 public override void evaluate()
 {
     if (pinInfo["writeToFile"].value.ToString() == _lastVal)
         return;
     _lastVal = pinInfo["writeToFile"].value.ToString();
     using (FileStream toWrite = File.Open(options.filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
     {
         switch (options.fileFormat)
         {
             case FileFormat.RSS:
                 SyndicationFeed feed;
                 try
                 {
                     feed = SyndicationFeed.Load(new XmlTextReader(toWrite)) ?? new SyndicationFeed(options.additionalInfo,"",options.publishURI);
                 }
                 catch (Exception)
                 {
                     feed = new SyndicationFeed(options.additionalInfo,"",options.publishURI);
                 }
                 List<SyndicationItem> items = new List<SyndicationItem>(feed.Items);
                 items.Add(new SyndicationItem("" , _lastVal , options.publishURI));
                 feed.Items = items;
                 XmlTextWriter xmlText = new XmlTextWriter(toWrite , Encoding.UTF8);
                 feed.SaveAsRss20(xmlText);
                 xmlText.Flush();
                 break;
             case FileFormat.Text:
                 //seek to append to the end of the file.
                 toWrite.Seek(0 , SeekOrigin.End);
                 StreamWriter writer = new StreamWriter(toWrite);
                 writer.WriteLine(_lastVal);
                 writer.Flush();
                 break;
             case FileFormat.Bin:
                 //this may be replaced by a binary type stream
                 BinaryFormatter bf = new BinaryFormatter();
                 bf.Serialize(toWrite,_lastVal);
                 toWrite.Flush();
                 break;
            /* case FileFormat.Database:
                 if (options.dataTransform == DataTransformation.None)
                     DatabaseHelper.SaveTo(options.connectionString , options.table , options.field , _lastVal);
                 else
                     DatabaseHelper.SaveTo(options.connectionString, options.table, options.dataTransform, _lastVal);
                 break;*/
         }
     }
 }
Example #14
0
        /// <summary>
        /// The write feed xml.
        /// </summary>
        /// <param name="feedType">
        /// The feed Type.
        /// </param>
        private void WriteFeedXml(FeedType feedType)
        {
            Settings app = SettingsComp.GetSettings();
            string url = app.Url;
            if (url == string.Empty)
            {
                Uri uri = System.Web.HttpContext.Current.Request.Url;
                string dnsPath = uri.Scheme + "://" + uri.Host;
                if (!uri.IsDefaultPort)
                {
                    dnsPath = dnsPath + ":" + uri.Port.ToString();
                }

                string appPath = System.Web.HttpContext.Current.Request.ApplicationPath;
                url = dnsPath + appPath;
            }

            if (url.Substring(url.Length - 1, 1) != "/")
            {
                url += "/";
            }

            List<PostInfo> posts = BlogComp.GetPosts();
            List<SyndicationItem> items = new List<SyndicationItem>();

            int count = 0;
            foreach (PostInfo post in posts)
            {
                if (++count > 20)
                {
                    break;
                }

                SyndicationItem item = new SyndicationItem();
                item.Title = SyndicationContent.CreatePlaintextContent(post.Title);

                TimeSpan ts = DateTime.UtcNow - DateTime.Now;
                item.PublishDate = new DateTimeOffset(post.Time, ts);

                string url2 = string.Format("{0}Post/{1}", url, post.FileID);
                SyndicationLink link = SyndicationLink.CreateAlternateLink(new Uri(url2));

                item.Links.Add(link);

                Post post2 = PostComp.GetPost(post.FileID);
                item.Content = SyndicationContent.CreateHtmlContent(post2.Contents);

                string catName = CategoryComp.GetCategoryName(post.CatID);
                item.Categories.Add(new SyndicationCategory(catName));

                items.Add(item);
            }

            SyndicationFeed feed = new SyndicationFeed(items);

            feed.Title = SyndicationContent.CreatePlaintextContent(app.Name);
            feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(url)));

            List<Author> authors = AuthorComp.GetAuthors();
            foreach (Author author in authors)
            {
                feed.Authors.Add(new SyndicationPerson(author.Email, author.Name, author.Url));
            }

            List<Category> catList = CategoryComp.GetCategories();
            foreach (Category cat in catList)
            {
                feed.Categories.Add(new SyndicationCategory(cat.Name));
            }

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = System.Text.Encoding.UTF8;
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;

            if (feedType == FeedType.RSS)
            {
                XmlWriter writer = XmlWriter.Create(this.Server.MapPath("~/App_Data/Rss.xml"), settings);
                feed.SaveAsRss20(writer);
                writer.Flush();
                writer.Close();
            }
            else
            {
                XmlWriter writer = XmlWriter.Create(this.Server.MapPath("~/App_Data/Atom.xml"), settings);
                feed.SaveAsAtom10(writer);
                writer.Flush();
                writer.Close();
            }
        }
 public SyndicationFeedResult(SyndicationFeed feed)
     : base()
 {
     using (var memstream = new MemoryStream())
     using (var writer = new XmlTextWriter(memstream, System.Text.UTF8Encoding.UTF8))
     {
     feed.SaveAsRss20(writer);
     writer.Flush();
     memstream.Position = 0;
     Content = new StreamReader(memstream).ReadToEnd();
     ContentType = "application/rss+xml" ;
     }
 }
Example #16
0
        public ActionResult Feed(string format)
        {
            var posts = _blogRepository.GetAll().OrderByDescending(b => b.PublishedDate);
            var items = new List<SyndicationItem>();

            foreach (var post in posts)
            {
                var feedItem = new SyndicationItem
                {
                    Content = new TextSyndicationContent(post.Content),
                    Id = post.Id.ToString(),
                    PublishDate = post.PublishedDate,
                    Title = new TextSyndicationContent(post.Title),
                };

                var url = String.Format(_configuration.Settings["Blog:UrlTemplate"],
                    post.PublishedDate.Year,
                    post.PublishedDate.Month.ToString().PadLeft(2, '0'),
                    post.Slug);

                feedItem.Links.Add(new SyndicationLink(new Uri(url)));

                items.Add(feedItem);
            }

            var feed = new SyndicationFeed(items);
            feed.Title = new TextSyndicationContent("Hadouken", TextSyndicationContentKind.Plaintext);
            feed.Description = new TextSyndicationContent("The Hadouken BitTorrent client blog feed",
                TextSyndicationContentKind.Plaintext);

            using (var ms = new MemoryStream())
            {
                var writer = XmlWriter.Create(ms);
                var contentType = "application/atom+xml";

                if (String.Equals("rss", format, StringComparison.InvariantCultureIgnoreCase))
                {
                    feed.SaveAsRss20(writer);
                    contentType = "application/rss+xml";
                }
                else
                {
                    feed.SaveAsAtom10(writer);
                }

                writer.Flush();

                var text = Encoding.UTF8.GetString(ms.ToArray());

                return Content(text, contentType, Encoding.UTF8);
            }
        }
Example #17
0
        private void GenerateRss(XElement element, ChildPages result, string outputFolder)
        {
            var rssUri = element.Attribute("RssUri").Value;
            var rssFeedName = element.Attribute("RssFeedName").Value;
            var rssAuthor = element.Attribute("RssAuthor").Value;
            var rssDescription = element.Attribute("RssDescription").Value;

            var feed = new SyndicationFeed(rssFeedName, rssDescription, new Uri(rssUri));
            feed.Authors.Add(new SyndicationPerson(rssAuthor));
            var feedItems = new List<SyndicationItem>();

            foreach (var page in result.Pages.Take(20))
            {
                var itemUri = rssUri + page.Location;
                var item = new SyndicationItem(page.Title, page.Content, new Uri(itemUri));
                item.PublishDate = new DateTimeOffset(page.Time);
                item.Id = page.Slurg;

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

                feedItems.Add(item);
            }

            feed.Items = feedItems;

            var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t" };

            var feedLocation = Path.Combine(outputFolder, "rss.xml");
            using (var writer = XmlWriter.Create(feedLocation, settings))
            {
                feed.SaveAsRss20(writer);
            }

            result.Rss = result.Name + "/" + "rss.xml";
        }
Example #18
0
		public void ProcessRequest(HttpContext context)
		{
			context.Response.ContentType = "text/xml";
			CultureInfo culture = DataLocalizationFacade.DefaultLocalizationCulture;

		    string pathInfo = context.Request.PathInfo;
            if (pathInfo.Length > 1)
			{
                culture = new CultureInfo(pathInfo.Substring(1));
			}

			using (var con = new DataConnection(culture))
			{
				var feed = new SyndicationFeed
				{
				    Title = new TextSyndicationContent("News List")
				};
			    var items = new List<SyndicationItem>();

			    IQueryable<NewsItem> allNews = con.Get<NewsItem>();

				string hostname = context.Request.Url.Host;
			    var hostnameBinding = con.Get<IHostnameBinding>().FirstOrDefault(h => h.Hostname == hostname);
				if (hostnameBinding != null)
				{
					Guid homepageId = hostnameBinding.HomePageId;
					var sm = new SitemapNavigator(con);
					var pagesFilter = new HashSet<Guid>(
                        sm.GetPageNodeById(homepageId)
                          .GetPageNodes(SitemapScope.DescendantsAndCurrent)
                          .Select(p => p.Id));

                    allNews = allNews.Evaluate().Where(n => pagesFilter.Contains(n.PageId)).ToList().AsQueryable();
				}

			    IEnumerable<NewsItem> latestNews = allNews.OrderByDescending(d => d.Date).Take(10);

				foreach (var news in latestNews.Evaluate())
				{
				    var page = PageManager.GetPageById(news.PageId);
				    if (page == null)
				    {
				        continue;
				    }

				    var pageUrlData = new PageUrlData(page) {PathInfo = NewsFacade.GetPathInfo(news.TitleUrl, news.Date)};
                    string pageUrl = PageUrls.BuildUrl(pageUrlData);
				    if (pageUrl == null)
				    {
				        continue;
				    }

					var item = new SyndicationItem(
						news.Title,
						news.Teaser,
						context.GetPath(pageUrl),
						news.Id.ToString(),
						news.Date
						);
					item.Categories.Add( new SyndicationCategory(news.PageId.ToString()) );
					items.Add(item);
				}
				feed.Items = items;
				var writer = new XmlTextWriter(context.Response.Output);
				feed.SaveAsRss20(writer);
			}
		}
Example #19
0
        public static void Main(string[] args)
        {
            Uri tokenUri = new Uri("https://api.twitter.com/oauth2/token");
            Uri userTimelineUri = new Uri("https://api.twitter.com/1.1/statuses/user_timeline.json");

            var twitter = new Twitter();

            var credential = new BearerTokenCredential(ConsumerKey, ConsumerSecret);
            var tokenRequest = new BearerTokenRequest(credential, tokenUri);

            IBearerToken token= twitter.RequestBearerToken(tokenRequest);

            Console.WriteLine(token);

            string screenName = "JohnRentoul";
            var tweetsRequest = new TweetRequest(token, userTimelineUri, screenName);

            var tweets = twitter.GetTweets(tweetsRequest);

            Console.WriteLine();
            Console.WriteLine("--------");
            Console.WriteLine();

            List<SyndicationItem> items = new List<SyndicationItem>();
            int counter = 0;
            foreach (var tweet in tweets)
            {
                if (tweet.ContainsLinks)
                {
                    counter++;
                    foreach (var link in tweet.Links)
                    {
                        Console.WriteLine(link.AbsoluteUri);
                    }

                    StringBuilder content = new StringBuilder();
                    content.AppendLine(tweet.text);
                    foreach(var link in tweet.Links)
                    {
                        string linkTag = string.Format(@"<a href='{0}'>{0}</>", link.AbsoluteUri);
                        content.AppendLine(linkTag);
                    }
                    SyndicationItem item = new SyndicationItem(screenName + counter, content.ToString(), new Uri("http://localhost"));
                    items.Add(item);
                }
            }

            var syndicationFeed = new SyndicationFeed("LinkTwrapper", "Tweets containing links", new Uri("http://localhost"))
                { Items = items };
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd_hhmmssfff");
            string filePath = string.Format(@"C:\WS\LinkTwrapper\RSSFiles\Tweets{0}.rss", timestamp);
            using (var fileStream = File.Create(filePath))
            {
                using (var xmlWriter = XmlWriter.Create(fileStream))
                {
                    syndicationFeed.SaveAsRss20(xmlWriter);
                    xmlWriter.Flush();
                }
            }

            Console.ReadLine();
        }
Example #20
0
        public static void Main(string[] args)
        {
            var options = new CommandLineOptions();
            var parser = new CommandLineParser(new CommandLineParserSettings(
                false /*case sensitive*/,
                false /*mutually exclusive*/,
                true  /*ignore unknown arguments*/,
                Console.Error));

            if (!parser.ParseArguments(args, options))
                Environment.Exit(1);

            Instapaper feeder = new Instapaper
            {
                Username = options.Username,
                Password = options.Password
            };
            feeder.OnMessage += (_, e) => Console.WriteLine(e.Message);

            foreach (var commandString in options.CommandsList)
            {
                CommandLineOptions.Commands command;
                if(!Enum.TryParse(commandString, true /*ignore case*/, out command))
                    continue;

                switch (command)
                {
                    case CommandLineOptions.Commands.list:
                        {
                            feeder.Directories.ForEach(d => Console.WriteLine(d.Name));

                            break;
                        }
                    case CommandLineOptions.Commands.rss:
                        {
                            var feedItems = (options.IncludeDirectories.Count == 0
                                ? feeder.Directories
                                : feeder.Directories.Where(directory => options.IncludeDirectories.Contains(directory.Name, StringComparer.OrdinalIgnoreCase)))
                                .SelectMany(d => d.GetFeedItems());

                            SyndicationFeed feed = new SyndicationFeed(feedItems);
                            using (var feedWriter = new XmlTextWriter(Environment.ExpandEnvironmentVariables(options.OutputFileName), Encoding.UTF8))
                            {
                                feed.SaveAsRss20(feedWriter);
                            }

                            break;
                        }
                    case CommandLineOptions.Commands.archive:
                        {
                            var directories = options.IncludeDirectories.Count == 0
                                ? feeder.Directories
                                : feeder.Directories.Where(directory => options.IncludeDirectories.Contains(directory.Name, StringComparer.OrdinalIgnoreCase));

                            foreach (var directory in directories)
                                directory.ArchivateAll();

                            break;
                        }
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
        }