protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.RssArticleList); RssArticles_textView = FindViewById <TextView>(Resource.Id.RssArticles_textView); RssArticles_listView = FindViewById <ListView>(Resource.Id.RssArticles_Listview); RssArticles_ProgressBar = FindViewById <ProgressBar>(Resource.Id.rssarticle_progressbar); articles_swipeRefreshLayout = FindViewById <SwipeRefreshLayout>(Resource.Id.articles_swipeRefreshLayout); long rssSourceId = this.Intent.GetLongExtra(HomeActivity.C_ARTICLE_URL, -1); RssSource rssSource = BddHelper.Instance.GetById(rssSourceId); RssArticles_ProgressBar.Visibility = Android.Views.ViewStates.Visible; string url = rssSource.Url; RssArticles_textView.Text = rssSource.Title; RefresDataListView(url); articles_swipeRefreshLayout.Refresh += async(sender, e) => { //await load(url); articles_swipeRefreshLayout.Refreshing = false; }; RegisterForContextMenu(RssArticles_listView); }
private void SeedRssSources(DigitalSignageContext pContext) { RssSource lRssSource1 = new RssSource() { Title = "Noticias de política TN", Description = "Noticias de la actualidad política, siendo su fuente Todo Noticias", URL = "http://tn.com.ar/feed/politica" }; RssSource lRssSource2 = new RssSource() { Title = "Noticias de deportes teleSur", Description = "Noticias de la actualidad deportiva, siendo su fuente teleSur", URL = "http://www.telesurtv.net/rss/RssDeporte.html" }; RssSource lRssSource3 = new RssSource() { Title = "Noticias de deportes El pais", Description = "Noticias de la actualidad deportiva, siendo su fuente el medio internacional El Pais", URL = "http://ep00.epimg.net/rss/deportes/portada.xml" }; pContext.RssSources.Add(lRssSource1); pContext.RssSources.Add(lRssSource2); pContext.RssSources.Add(lRssSource3); pContext.SaveChanges(); }
/// <summary> /// Eliminar una fuente RSS /// </summary> /// <param name="pRssSourceDTO">fuente RSS que se desea eliminar</param> public void Remove(RssSourceDTO pRssSourceDTO) { try { var asociatedBanners = iUnitOfWork.RssSourceRepository.GetBannersWithSource(pRssSourceDTO.Id); if (asociatedBanners.ToList().Count == 0) { log.Info("Eliminando fuente RSS"); RssSource RssSource = iUnitOfWork.RssSourceRepository.Get(pRssSourceDTO.Id); iUnitOfWork.RssSourceRepository.Remove(RssSource); iUnitOfWork.Complete(); log.Info("fuente RSS eliminada con exito"); } else { throw new Exception("No se puede eliminar la fuente RSS ya que esta siendo usada por banners"); } } catch (ArgumentNullException e) { log.Error("Error al eliminar fuente RSS: " + e.Message); throw new ArgumentException(); } }
private async Task GetNews(RssSource source) { IRssService rssService; string sourceName; switch (source) { case RssSource.Undefined: throw new ArgumentOutOfRangeException(); case RssSource.BBC: rssService = new RssServiceBBC(); sourceName = "BBC"; break; case RssSource.Google: rssService = new RssServiceGoogle(); sourceName = "Google"; break; default: throw new ArgumentOutOfRangeException(); } var items = await rssService.GetRssItems(); Console.WriteLine($"Receiving data from {sourceName}"); await _dataService.SaveRssItemsAsync(items); Console.WriteLine($"Received {items.Length} items"); }
public ActionResult Create(RssSource rssSource) { if (ControllerContext.HttpContext.Request.IsAjaxRequest()) { if (ModelState.IsValid) { repository.Add(rssSource); var result = new HandlerResult { IsSuccess = true, Message = "添加RSS源成功" }; return(Json(result)); } else { var result = new HandlerResult { IsSuccess = false, Message = "添加RSS源失败" }; return(Json(result)); } } else { if (ModelState.IsValid) { var flag = repository.Add(rssSource); return(Redirect("Index")); } else { return(View(rssSource)); } } }
private byte[] GetLogo(RssSource source) { string path = string.Empty; if (source == RssSource.BBC) { path = $"{_configuration.GetValue<string>("Logos:RootFolder")}BBC.png"; } else if (source == RssSource.CNN) { path = $"{_configuration.GetValue<string>("Logos:RootFolder")}CNN.png"; } else if (source == RssSource.Reuters) { path = $"{_configuration.GetValue<string>("Logos:RootFolder")}REUTERS.png"; } byte[] result; using (FileStream img = new FileStream(path, FileMode.Open, FileAccess.Read)) { using (var ms = new MemoryStream()) { img.CopyTo(ms); result = ms.ToArray(); } } return(result); }
private static async Task GetNews(RssSource source) { IRssService rssService; string sourceName; switch (source) { case RssSource.Undefined: throw new ArgumentOutOfRangeException(); case RssSource.Prokazan: rssService = new RssServiceProkazan(); sourceName = "Prokazan"; break; case RssSource.RtOnline: rssService = new RssServiceRtOnline(); sourceName = "Rtonline"; break; case RssSource.BusinessGazeta: rssService = new RssServiceBusinessGazeta(); sourceName = "BusinessGazeta"; break; default: throw new ArgumentOutOfRangeException(); } Console.WriteLine($"Получение данных с {sourceName}"); var rssItems = rssService.GetRssItems(); Console.WriteLine($"Получено {rssItems.Length} статей"); await _dataService.SaveRssItems(rssItems); }
public int Add(RssSource rssSource) { using (var cnx = new SQLiteConnection(connectionString)) { cnx.Insert(rssSource); } return(rssSource.Id); }
/// <summary> /// Executes the import of RSS feeds from BBC News /// </summary> private void ImportDailymail() { RssSource dailymail = new RssSource(); Console.WriteLine("Importing Dailymail RSS Feeds..."); dailymail.StartImport(); Console.WriteLine(dailymail.ReturnImportMessage()); Console.WriteLine(" "); _totalImported = _totalImported + dailymail.ReturnImportNumber(); }
public void Save(RssSource rssSource) { using (var cnx = new SQLite.SQLiteConnection(Path)) { // création de la table si elle n'existe pas cnx.CreateTable <RssReader.Models.RssSource>(); //insertion de la données contenu dans l'objet au format de celui-ci cnx.Insert(rssSource); } }
public void ReadXmlFile(string route) { XmlDocument xDoc = new XmlDocument(); StreamReader reader = File.OpenText(route); string textFromFile; textFromFile = reader.ReadToEnd(); try { xDoc.LoadXml(textFromFile); } catch (Exception e) { correctTextForXmlCreation(ref textFromFile); xDoc.LoadXml(textFromFile); } XmlNode rssChannelRoot = xDoc.SelectSingleNode("rss/channel"); string sourceName = rssChannelRoot.SelectSingleNode("title").InnerText.Trim(); string sourceUrl = rssChannelRoot.SelectSingleNode("link").InnerText.Trim(); RssSource source = RssRepository.Sources.FirstOrDefault(s => s.Name == sourceName && s.Url == sourceUrl); if (source == null) { source = new RssSource(); source.Name = sourceName; source.Url = sourceUrl; } XmlNodeList itemsNodes = rssChannelRoot.SelectNodes("item"); int numberOfSavedEntities = 0; foreach (XmlNode itemNode in itemsNodes) { Novelty item = new Novelty(); string title = itemNode.SelectSingleNode("title").InnerText.Trim(); clearDataFromHtmlElements(ref title); item.Header = title; item.Date = DateTime.Parse(itemNode.SelectSingleNode("pubDate").InnerText.Trim()); Novelty dbEntry = RssRepository.News.FirstOrDefault(n => n.Date == item.Date && n.Header == item.Header); if (dbEntry == null) { item.Url = itemNode.SelectSingleNode("guid").InnerText.Trim(); string description = itemNode.SelectSingleNode("description").InnerText.Trim(); clearDataFromHtmlElements(ref description); item.Description = description; item.Source = source; RssRepository.AddNovelty(item); numberOfSavedEntities++; } } Console.WriteLine("Источник новостей: {0}", source.Name); Console.WriteLine("Прочитано новостей: {0}", itemsNodes.Count); Console.WriteLine("Сохранено новостей: {0}", numberOfSavedEntities); }
/// <summary> /// Добавить источник из URL /// </summary> /// <param name="uri">URL</param> /// <returns></returns> private async Task <Guid> AddSourceFromUri(string uri) { var feed = await FeedReader.ReadAsync(uri); RssSource source = new RssSource(uri, feed.Title); _context.RssSources.Add(source); await _context.SaveChangesAsync(); await AddItems(source.RssSourceGuid, feed.Items); return(source.RssSourceGuid); }
public void ModifySource(RssSourceDTO pDto) { iUoW.BeginTransaction(); try { RssSource lSource = Mapper.Map <RssSourceDTO, RssSource>(pDto); iServ.Update(lSource); iUoW.Commit(); } catch (Exception) { iUoW.Rollback(); throw; } }
public void Update(RssSource obj, out OperationResult operationResult) { lock (Lock) { if (obj == null) { operationResult = new OperationResult { Type = OperationResult.ResultType.Warning }; return; } Common.Instance.Update (obj, objs => objs.RssSourceId == obj.RssSourceId && objs.LanguageId == obj.LanguageId, out operationResult); } }
public void DeleteSource(RssSourceDTO pDto) { iUoW.BeginTransaction(); try { RssSource lSource = Mapper.Map <RssSourceDTO, RssSource>(pDto); iServ.Delete(pDto.Id); iUoW.Commit(); } catch (Exception) { iUoW.Rollback(); throw; } }
public void Insert(RssSource obj, out OperationResult operationResult) { lock (Lock) { if (obj == null) { operationResult = new OperationResult { Type = OperationResult.ResultType.Warning }; } else { Common.Instance.Insert(obj, out operationResult); } } }
public int AddSource(RssSourceDTO pDto) { iUoW.BeginTransaction(); try { RssSource lSource = Mapper.Map <RssSourceDTO, RssSource>(pDto); iServ.Create(lSource); iUoW.Commit(); return(lSource.Id); } catch (Exception) { iUoW.Rollback(); throw; } }
public override async void ViewDidLoad() { base.ViewDidLoad(); item = rssReaderService.GetRssSourceById(Id); Title = item.Title; refreshControl = new UIRefreshControl(); refreshControl.ValueChanged += RefreshControl_ValueChanged; rssitemslistview.Add(refreshControl); var _ = Load(); }
/// <summary> /// Closes connection to file. /// </summary> /// <remarks> /// This method also releases any resources held while reading. /// </remarks> public void Close() { this.textInput = null; this.image = null; this.cloud = null; this.channel = null; this.source = null; this.enclosure = null; this.category = null; this.item = null; if (this.reader != null) { this.reader.Close(); this.reader = null; } this.elementText = null; this.xmlNodeStack = null; }
public override async void ViewDidLoad() { base.ViewDidLoad(); RssSource rssSource = BddHelper.Instance.GetById(Id); loader.StartAnimating(); var rssArticle = await RssApi.GetArticles(rssSource.Url); loader.StopAnimating(); loader.Hidden = true; RssArticlesTableViewSource rssArticlesTableViewSource = new RssArticlesTableViewSource(rssArticle); RssArticlesTableView.Source = rssArticlesTableViewSource; this.Title = rssSource.Title; }
/// <summary> /// Crea una fuente RSS /// </summary> /// <param name="pRssSourceDTO">fuente RSS que se quiere crear</param> public void Create(RssSourceDTO pRssSourceDTO) { ///Mapea el DTO a un objecto RssSource var rssSource = new RssSource(); AutoMapper.Mapper.Map(pRssSourceDTO, rssSource); try { log.Info("Guardando fuente RSS"); this.iUnitOfWork.RssSourceRepository.Add(rssSource); this.iUnitOfWork.Complete(); log.Info("fuente RSS creada con exito"); } catch (ArgumentException e) { log.Error("Error al crear fuente RSS: " + e.Message); throw new ArgumentException(); } }
public void MakeRssFile() { RssSource[] items = new RssSource[] { new RssSource() { Company = "DateLine NBC", Address = "https://podcastfeeds.nbcnews.com/dateline-nbc" }, new RssSource() { Company = "The Daily by the New Your Times", Address = "http://rss.art19.com/the-daily" }, new RssSource() { Company = "The Experiment", Address = "http://feeds.wnyc.org/experiment_podcast" }, new RssSource() { Company = "Netflix SEC Filings", Address = "https://ir.netflix.net/rss/SECFiling.aspx?Exchange=CIK&Symbol=0001065280" }, new RssSource() { Company = "Google", Address = "https://feeds.feedburner.com/google/think" }, }; rssSourcesCount = items.Length; try { using StreamWriter writer = new StreamWriter(fileName); var json = JsonSerializer.Serialize <RssSource[]>(items); writer.Write(json); writer.Close(); Console.WriteLine($"Created RSS file: \"{fileName}\""); } catch (Exception ex) { Console.WriteLine($"ERROR Creating RSS file: \"{fileName}\"\n{ex.Message}"); } }
public int AddRssSource(string title, string url) { if (string.IsNullOrEmpty(title)) { throw new AddRssSourceTitleRequiredException(); } if (!(Uri.TryCreate(url, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps))) { throw new AddRssSourceUrlRequiredException(); } var rssSource = new RssSource { Title = title, Url = url, CreatedAt = DateTime.Now }; return(rssSourceRepository.Add(rssSource)); }
/// <summary> /// Добавить пустой источник /// </summary> /// <param name="title">Название источника</param> /// <returns></returns> private async Task <Guid> AddEmptySource(string title) { RssSource source = new RssSource(title); _context.RssSources.Add(source); await _context.SaveChangesAsync(); RssItem item = new RssItem() { Description = "Создан канал: " + source.Title, PubDate = DateTimeOffset.Now, RssItemGuid = Guid.NewGuid(), RssSourceGuid = source.RssSourceGuid, Title = "Создание канала" }; _context.RssItems.Add(item); await _context.SaveChangesAsync(); return(source.RssSourceGuid); }
/// <summary> /// Actualiza una fuente RSS /// </summary> /// <param name="pRssSourceDTO">fuente RSS que se desea actualizar</param> public void Update(RssSourceDTO pRssSourceDTO) { ///fuente RSS actualizada var RssSource = new RssSource(); AutoMapper.Mapper.Map(pRssSourceDTO, RssSource); try { //fuente RSS anterior log.Info("Actualizando fuente RSS"); iUnitOfWork.RssSourceRepository.Update(RssSource); //Guardando los cambios iUnitOfWork.Complete(); } catch (Exception e) { log.Error("Error al actualizar fuente RSS: " + e.Message); throw new Exception(); } }
protected override async void OnCreate(Bundle savedInstanceState) { rssReaderService = new RssReaderService(Constants.ConnectionString); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_rssitems); var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); SupportActionBar.SetHomeButtonEnabled(true); SupportActionBar.SetDisplayHomeAsUpEnabled(true); itemsSwipeRefreshLayout = FindViewById <SwipeRefreshLayout>(Resource.Id.rssitems_swiperefreshlayout); itemsRecyclerview = FindViewById <RecyclerView>(Resource.Id.rssitems_itemsRecyclerview); itemsRecyclerview.SetLayoutManager(new LinearLayoutManager(this)); //itemsRecyclerview.SetLayoutManager(new GridLayoutManager(this, 2)); // https://www.lemonde.fr/rss/une.xml // Recuperer l'element depuis l'id var id = Intent.GetIntExtra("ID", -1); if (id != -1) { item = rssReaderService.GetRssSourceById(id); SupportActionBar.Title = item.Title; itemsSwipeRefreshLayout.Refresh += ItemsSwipeRefreshLayout_Refresh; var _ = Load(); } }
public RssSource ReadOne(string feedUrl) { var result = new RssSource { FeedUrl = feedUrl}; var feed = new RssFeed(); feed.Load(new Uri(feedUrl), null); feed.Channel.Items .ToList() .ForEach(x => { if (x.Enclosures != null && x.Enclosures.Any(m => m.ContentType.ToLower().Contains("mp3"))) { var item = new RssSourceItem { Title = x.Title, Description = x.Description, Link = x.Link.ToString(), Mp3 = x.Enclosures.First(mp3 => mp3.ContentType.ToLower().Contains("mp3")).Url.ToString() }; item.PublicationDate = x.PublicationDate; result.Items.Add(item); } }); return result; }
public void OnRssSourceDeleted(RssSource item) { rssReaderService.DeleteRssSource(item.Id); rsssourcestableview.ReloadData(); }
public async Task Parse(RssSource rssSource) { var _UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; httpClient.DefaultRequestHeaders.Add("user-agent", _UserAgent); var response = await httpClient.GetStringAsync(rssSource.Url); XNamespace xmlns = "http://www.w3.org/2005/Atom"; XNamespace media = "http://search.yahoo.com/mrss/"; XDocument Feed = XDocument.Parse(response); string group = rssSource.Group.Length > 1 ? rssSource.Group : Feed.Descendants("channel").Select(e => (string)e.Element("title").Value).First(); IEnumerable <Item> items = new List <Item>(); if (rssSource.Url.StartsWith("http://gdata.youtube.com/feeds/api/playlists/")) //parse Youtube Playlist RSS { //0 is link, 1 is image, 2 is title, 3 is description string youtubeHtmlTemplate = "<p><a href=\"{0}\"><img src=\"{1}\" alt=\"\" width=300></a></p><p><a style=\"font-size: 15px; font-weight: bold; font-decoration: none;\" href=\"{0}\">{2}</a></p><p>{3}</p>"; items = from item in Feed.Descendants("item") select new Item() { Title = item.Element("title").Value, Subtitle = item.Element("pubDate").Value, Description = item.Descendants(media + "thumbnail").Count() > 0 ? string.Format(youtubeHtmlTemplate, item.Element("link").Value, item.Descendants(media + "thumbnail").Select(e => (string)e.Attribute("url")).FirstOrDefault(), item.Element("title").Value, item.Element("description").Value.Substring(0, Math.Min(580, item.Element("description").Value.Length))) : string.Empty, Image = item.Descendants(media + "thumbnail") != null?item.Descendants(media + "thumbnail").Select(e => (string)e.Attribute("url")).FirstOrDefault() : string.Empty, Group = @group, }; items = items.Where(x => x.Description != string.Empty); } else { string audio_template = "<audio src=\"{0}\" controls autoplay>Your browser does not support the <code>audio</code> element.<br/><a href=\"{0}\">Link to file</a>.</audio><br/>"; var feeditems = AppSettings.RssMaxItemsPerFeed < 0 ? Feed.Descendants("item") : Feed.Descendants("item").Take(AppSettings.RssMaxItemsPerFeed); items = from item in feeditems select new Item() { Title = item.Element("title") != null?item.Element("title").Value : string.Empty, Subtitle = item.Element("pubDate") != null?item.Element("pubDate").Value : string.Empty, Description = // TODO: perhaps this needs to use the url's MIME type to determine the tag for audio, video, PDFs, etc.? (item.Element("enclosure") != null ? string.Format(audio_template, (string)(item.Element("enclosure").Attribute("url"))) : string.Empty) + (item.Element("description") != null ? (string)(item.Element("description").Value) : string.Empty), Image = item.Descendants(media + "thumbnail") != null?item.Descendants(media + "thumbnail").Select(e => (string)e.Attribute("url")).FirstOrDefault() : "", Group = @group, }; } if (items.ToList().Count > 0) { foreach (var item in items) { if (item.Image == null) //Attempt to parse an image out of the description if one is not returned in the RSS { item.Image = Regex.Match(item.Description, "(https?:)?//?[^'\"<>]+?.(jpg|jpeg|gif|png)").Value; } //Format dates to look cleaner DateTime dateTimeResult = new DateTime(); if (DateTime.TryParse(item.Subtitle, out dateTimeResult)) { item.Subtitle = dateTimeResult.ToString("ddd, d MMM yyyy"); } RssData.Add(item); } ; } else { await ServiceLocator.MessageService.ShowErrorAsync("Zero items retrieved from " + rssSource.Url, "Application Error"); } }
public void AddSource(RssSource entity) { context.Sources.Add(entity); context.SaveChanges(); }
public IActionResult Create(RssSource rssSource) { return(View()); }