public async Task GetFeed()
        {
            try
            {
                SyndicationClient client = new SyndicationClient();
                SyndicationFeed   feed;

                // Although most HTTP servers do not require User-Agent header,
                // others will reject the request or return a different response if this header is missing.
                // Use the setRequestHeader() method to add custom headers.
                client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
                feed = await client.RetrieveFeedAsync(this.uri);

                // Retrieve the title of the feed and store it in a string.
                string title = feed.Title.Text;
                // Iterate through each feed item.
                feedItems = new List <T>();
                foreach (SyndicationItem item in feed.Items)
                {
                    try
                    {
                        feedItems.Add(ObjectFactory(item));
                    }
                    catch { }
                }
                RSSItemsChanged?.Invoke(this, new EventArgs());
                lastUpdated = DateTime.Now;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
        }
Exemple #2
0
        private async Task GetFeed()
        {
            lock (_lock)
            {
                if (lastUpdated > DateTime.Now.Subtract(new TimeSpan(6, 0, 0)))
                {
                    return;
                }
                lastUpdated = DateTime.Now;
            }
            SyndicationClient client = new SyndicationClient();
            SyndicationFeed   feed;

            string uriString = @"https://www.fantasyflightgames.com/en/rss/?tags=x-wing&";
            Uri    uri       = new Uri(uriString);

            try
            {
                // Although most HTTP servers do not require User-Agent header,
                // others will reject the request or return a different response if this header is missing.
                // Use the setRequestHeader() method to add custom headers.
                client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
                feed = await client.RetrieveFeedAsync(uri);

                // Retrieve the title of the feed and store it in a string.
                string title = feed.Title.Text;
                // Iterate through each feed item.
                FeedItems = feed.Items.ToList();
            }
            catch (Exception ex)
            {
                lastUpdated = DateTime.MinValue;
            }
        }
        private async void GetFeed_Click(object sender, RoutedEventArgs e)
        {
            outputField.Text = "";

            // By default 'FeedUri' is disabled and URI validation is not required. When enabling the text box
            // validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(FeedUri.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Error: Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            SyndicationClient client = new SyndicationClient();

            client.BypassCacheOnRetrieve = true;

            // Although most HTTP servers do not require User-Agent header, others will reject the request or return
            // a different response if this header is missing. Use SetRequestHeader() to add custom headers.
            client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            rootPage.NotifyUser("Downloading feed...", NotifyType.StatusMessage);
            outputField.Text = "Downloading feed: " + uri.ToString() + "\r\n";

            try
            {
                currentFeed = await client.RetrieveFeedAsync(uri);

                rootPage.NotifyUser("Feed download complete.", NotifyType.StatusMessage);

                DisplayFeed();
            }
            catch (Exception ex)
            {
                SyndicationErrorStatus status = SyndicationError.GetStatus(ex.HResult);
                if (status == SyndicationErrorStatus.InvalidXml)
                {
                    outputField.Text += "An invalid XML exception was thrown. " +
                                        "Please make sure to use a URI that points to a RSS or Atom feed.";
                }

                if (status == SyndicationErrorStatus.Unknown)
                {
                    WebErrorStatus webError = WebError.GetStatus(ex.HResult);

                    if (webError == WebErrorStatus.Unknown)
                    {
                        // Neither a syndication nor a web error. Rethrow.
                        throw;
                    }
                }

                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
        }
Exemple #4
0
        private static SyndicationClient GetSyndicationClient()
        {
            var client = new SyndicationClient
            {
                BypassCacheOnRetrieve = false
            };

            client.SetRequestHeader("user-agent", USER_AGENT);
            return(client);
        }
Exemple #5
0
        private async void updateHorribleFeed()
        {
            if (!Uri.TryCreate(HORRIBLE_URL.Trim(), UriKind.Absolute, out uri))
            {
                StatusMessage.Text = "Error: Invalid HorribleSub URI";
                return;
            }
            SyndicationClient client = new SyndicationClient();

            client.BypassCacheOnRetrieve = true;
            client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            this.uri = new Uri(HORRIBLE_URL);
            this.currentHorribleFeed = await client.RetrieveFeedAsync(this.uri);

            DisplayHorribleFeed();
        }
Exemple #6
0
        public async void syndication()
        {
            SyndicationClient client = new SyndicationClient();

            //uri写在外面,为了在try之外不会说找不到变量
            Uri uri = null;

            //uri字符串
            string uri_string = "http://www.win10.me/?feed=rss2";

            try
            {
                uri = new Uri(uri_string);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            try
            {
                //模拟http
                // 如果没有设置可能出错
                client.SetRequestHeader("User-Agent",
                                        "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

                SyndicationFeed feed = await client.RetrieveFeedAsync(uri);

                foreach (SyndicationItem item in feed.Items)
                {
                    display_current_item(item);
                }

                //foreach (var temp in rsslist)
                //{
                //    reminder = temp.summary;
                //}
            }
            catch
            {
                // Handle the exception here.
            }
        }
        private static async Task <SyndicationFeed> GetMSDNBlogFeed()
        {
            SyndicationFeed feed = null;

            try
            {
                SyndicationClient client = new SyndicationClient();
                client.BypassCacheOnRetrieve = true;
                client.SetRequestHeader(customHeaderName, customHeaderValue);

                feed = await client.RetrieveFeedAsync(new Uri(feedUrl));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return(feed);
        }
Exemple #8
0
        /// <summary>
        /// 从URL获取解析后的Channel的信息
        /// </summary>
        /// <param name="url">地址</param>
        /// <returns></returns>
        public static async Task <Channel> GetChannelFromUrl(string url)
        {
            var client = new SyndicationClient();

            client.Timeout = 15000;
            var feed = new SyndicationFeed();

            client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            try
            {
                feed = await client.RetrieveFeedAsync(new Uri(url));

                if (feed != null)
                {
                    return(new Channel(feed, url));
                }
            }
            catch (Exception)
            {
            }
            return(null);
        }
        //Returns feed name for a given feed Uri
        private async Task <string> FetchFeedNameAsync(string argUriString)
        {
            try
            {
                SyndicationClient client = new SyndicationClient();
                client.SetRequestHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
                SyndicationFeed feed = await client.RetrieveFeedAsync(new Uri(argUriString));

                if (feed != null)
                {
                    return(feed.Title.Text);
                }
                else
                {
                    return("Unknown name");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return("Unknown name");
            }
        }
Exemple #10
0
        public async Task <IList <SyndicationFeed> > DownloadFeedsAsync(User currentUser = null)
        {
            var results = new List <SyndicationFeed>();

            using (var db = new AppDbContext())
            {
                if (currentUser == null)
                {
                    currentUser = db.Users.SingleOrDefault(u => u.LastLoggedIn == true);
                }

                SyndicationClient client = new SyndicationClient();
                client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

                foreach (Subscription f in db.Subscriptions.Where(u => u.UserID == currentUser.ID)
                         .Include(r => r.RssFeed).ToList())
                {
                    try
                    {
                        Uri uri = new Uri(f.RssFeed.Uri);
                        //TODO: timeoutot
                        SyndicationFeed feed = await client.RetrieveFeedAsync(uri);

                        feed.Items.OrderBy(i => i.PublishedDate);
                        results.Add(feed);
                    }
                    catch (COMException e) when(RssExceptionFilter(e) == true)
                    {
                        //lehet nincs internet, vagy a DNS szerver nem elérhetö
                    }
                    catch (UriFormatException e)
                    {
                    }
                }
            }
            return(results);
        }
Exemple #11
0
        //Download content for a subscription, save it to LocalCache and add it to the collection
        private async Task CacheFeed(ApplicationDataCompositeValue argFeedSubscription)
        {
            try
            {
                SyndicationClient client = new SyndicationClient();
                client.SetRequestHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
                string          feedUriString = argFeedSubscription.ElementAt(1).Value.ToString();
                SyndicationFeed feed          = await client.RetrieveFeedAsync(new Uri(feedUriString));

                if (feed != null)
                {
                    feedsCollection.Clear();

                    //Cache my content cache files to LocalCache inside per feed folder
                    //Create folder if it does not exist
                    string        folderName      = CreateValidFilename(feedUriString);
                    StorageFolder myStorageFolder = await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

                    //Delete any old files in folder
                    IReadOnlyList <StorageFile> fileListLocalCache = await myStorageFolder.GetFilesAsync();

                    foreach (StorageFile file in fileListLocalCache)
                    {
                        await file.DeleteAsync();
                    }

                    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                    int postLimit = int.Parse(localSettings.Values["#postsToDownload"].ToString());

                    //Cache every article
                    foreach (SyndicationItem mySyndicationItem in feed.Items)
                    {
                        //Do not cache more posts that specified by user setting
                        if (feedsCollection.Count == postLimit)
                        {
                            break;
                        }

                        CustomRSSItem myCustomRSSItem = null;

                        //Cache posts
                        string          articleFileName = "";
                        Regex           rgx1            = new Regex(@".*/(.+)");
                        MatchCollection matches1        = rgx1.Matches(mySyndicationItem.Id);
                        if (matches1.Count > 0)
                        {
                            articleFileName = CreateValidFilename(matches1[0].Groups[1].Value);
                            var          xmlDoc         = mySyndicationItem.GetXmlDocument(SyndicationFormat.Atom10);
                            IStorageFile myIStorageFile = await myStorageFolder.CreateFileAsync(articleFileName, CreationCollisionOption.ReplaceExisting);

                            await xmlDoc.SaveToFileAsync(myIStorageFile);

                            //Download and cache images
                            BitmapImage myBitmapImage = null;

                            //Get image from thumbnail element
                            var thumbnails = xmlDoc.GetElementsByTagName("thumbnail");
                            if (thumbnails.Count > 1)
                            {
                                string thumbnailUriString = thumbnails[1].Attributes[0].InnerText;
                                if (thumbnailUriString.EndsWith(".jpg"))
                                {
                                    Uri    uriForImage   = new Uri(thumbnailUriString);
                                    string imageFileName = CreateValidFilename(thumbnailUriString);
                                    if (imageFileName.Length > 50)
                                    {
                                        imageFileName = imageFileName.Substring(imageFileName.Length - 50);
                                    }
                                    HttpClient httpClient = new HttpClient();
                                    httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
                                    IBuffer myIBuffer = await httpClient.GetBufferAsync(uriForImage);

                                    IStorageFile myImageFile = await myStorageFolder.CreateFileAsync(imageFileName, CreationCollisionOption.OpenIfExists);

                                    Stream stream = await myImageFile.OpenStreamForWriteAsync();

                                    stream.Write(myIBuffer.ToArray(), 0, myIBuffer.ToArray().Length);
                                    myBitmapImage = new BitmapImage(new Uri(myImageFile.Path));
                                    await stream.FlushAsync();
                                }
                            }
                            else
                            //Retrieve .jpg from img link from summary text
                            {
                                Regex           rgx     = new Regex(@"<img.*src=""(.*)""");
                                MatchCollection matches = rgx.Matches(mySyndicationItem.Summary.Text);
                                if (matches.Count > 0)
                                {
                                    string stringForImage = matches[0].Groups[1].Value;
                                    //If Uri has & parameters remove them
                                    stringForImage = RemoveAmpFromUri(stringForImage);
                                    Uri uriForImage = new Uri(stringForImage);

                                    string imageFileName = CreateValidFilename(uriForImage.ToString());
                                    if (imageFileName.Length > 50)
                                    {
                                        imageFileName = imageFileName.Substring(imageFileName.Length - 50);
                                    }
                                    imageFileName = AddExtension(imageFileName);
                                    HttpClient httpClient = new HttpClient();
                                    IBuffer    myIBuffer  = await httpClient.GetBufferAsync(uriForImage);

                                    IStorageFile myImageFile = await myStorageFolder.CreateFileAsync(imageFileName, CreationCollisionOption.ReplaceExisting);

                                    Stream stream = await myImageFile.OpenStreamForWriteAsync();

                                    stream.Write(myIBuffer.ToArray(), 0, myIBuffer.ToArray().Length);
                                    myBitmapImage = new BitmapImage(new Uri(myImageFile.Path));
                                }
                            }

                            if (myBitmapImage != null)
                            {
                                //If we have an RSSItem and an image, add them to collection
                                myCustomRSSItem = new CustomRSSItem(mySyndicationItem, myBitmapImage);
                                feedsCollection.Add(myCustomRSSItem);
                            }
                        }
                    }
                    articlesListView.ItemsSource = feedsCollection;
                    //Copy what was just cached to SharedLocal
                    Task t = CopyLocalCacheToSharedLocal(argFeedSubscription);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }