Esempio n. 1
0
        public void BasicEverythingRequestWorks()
        {
            var everythingRequest = new EverythingRequest
            {
                Q = "bitcoin"
            };

            var result = NewsApiClient.GetEverything(everythingRequest);

            Assert.Equal(Statuses.Ok, result.Status);
            Assert.True(result.TotalResults > 0);
            Assert.True(result.Articles.Count > 0);
            Assert.Null(result.Error);
        }
Esempio n. 2
0
        public List <NewsModel> GetListNews(string keyphrase, DateTime fromDate)
        {
            var newsApiClient    = new NewsApiClient("c3eb90f31b2946d29c9ffca8cd9c2626");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = keyphrase,
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = fromDate
            });

            var list = new List <NewsModel>();

            for (var i = 0; i < 8; i++)
            {
                var news = new NewsModel()
                {
                    Title = articlesResponse.Articles[i].Title,
                    Url   = articlesResponse.Articles[i].Url,
                    From  = articlesResponse.Articles[i].Source.Name
                };
                list.Add(news);
            }

            return(list);
        }
Esempio n. 3
0
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            // init with your API key
            var newsApiClient    = new NewsApiClient("5a6f078ea39446cda5b9698ccd4e26be");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = "Apple",
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = new DateTime(2018, 1, 25)
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                // total results found
                Console.WriteLine(articlesResponse.TotalResults);
                // here's the first 20
                foreach (var article in articlesResponse.Articles)
                {
                    // title
                    Console.WriteLine(article.Title);
                    // author
                    Console.WriteLine(article.Author);
                    // description
                    Console.WriteLine(article.Description);
                    // url
                    Console.WriteLine(article.Url);
                    // published at
                    Console.WriteLine(article.PublishedAt);
                }
            }
            Console.ReadLine();
        }
Esempio n. 4
0
        public static void Main(string[] args)
        {
            string usuarioSQL  = ConfigurationSettings.AppSettings["usuarioSQL"];
            string servidorSQL = ConfigurationSettings.AppSettings["servidorSQL"];
            string passwordSQL = ConfigurationSettings.AppSettings["passwordSQL"];
            string bd          = ConfigurationSettings.AppSettings["bdSQL"];

            string cnnStr = "Data Source=" + servidorSQL + ";Initial Catalog=" + bd + ";User ID=" + usuarioSQL + ";Password="******"";

            SqlConnection cnn = new SqlConnection(cnnStr);

            cnn.Open();
            // init with your API key
            var newsApiClient    = new NewsApiClient("a55ecdd5ddd34f279b3b9e1ffd1eefa9");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = "La casa de papel",
                SortBy   = SortBys.Popularity,
                Language = Languages.ES,
                From     = new DateTime(2018, 6, 13),
                PageSize = 100
            });

            //var articulos = newsApiClient.GetTopHeadlines(new EverythingRequest {Page="www"})

            string     queryDelete = "delete from noticias";
            SqlCommand command2    = new SqlCommand(queryDelete, cnn);

            command2.ExecuteNonQuery();

            if (articlesResponse.Status == Statuses.Ok)
            {
                // total results found
                Console.WriteLine(articlesResponse.TotalResults);
                // here's the first 20
                foreach (var article in articlesResponse.Articles)
                {
                    // title
                    Console.WriteLine(article.Title);
                    // author
                    Console.WriteLine(article.Author);
                    // description
                    Console.WriteLine(article.Description);
                    // url
                    Console.WriteLine(article.Url);
                    // image
                    Console.WriteLine(article.UrlToImage);
                    // published at
                    Console.WriteLine(article.PublishedAt);
                    Console.WriteLine(article.Source.Id);
                    Console.WriteLine(article.Source.Name);

                    string     queryControl = "insert into NOTICIAS(TITULO,AUTOR,DESCRIPCION,URL,URLTOIMAGE,PUBLICADO,FUENTE_ID,FUENTE_NOMBRE) values('" + article.Title.Replace("'", "") + ")','" + article.Author + "','" + article.Description + "','" + article.Url + "','" + article.UrlToImage + "','" + article.PublishedAt + "','" + article.Source.Id + "','" + article.Source.Name + "')";
                    SqlCommand command      = new SqlCommand(queryControl, cnn);
                    command.ExecuteNonQuery();
                }
            }
            cnn.Close();
            Console.ReadLine();
        }
Esempio n. 5
0
        public ActionResult <IEnumerable <News> > Get(string search)
        {
            var newsApiKey = "baa2e97368c5442aba7a2d47c77e3258";

            var list = new List <News>();

            var newsApiClient    = new NewsApiClient(newsApiKey);
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = search,
                SortBy   = SortBys.Popularity,
                Language = Languages.PL,
                From     = new DateTime(2019, 6, 15),
            });

            var tmp = new List <Article>();

            tmp = articlesResponse.Articles;


            foreach (var item in tmp)
            {
                var name = new string(item.Title);

                var desp = new string(item.Description);
                var url  = new string(item.Url);

                list.Add(new News(name, desp, url));
            }



            return(list);
        }
Esempio n. 6
0
        public async Task <ActionResult <FeedListingModel> > Get()
        {
            var feedList = new FeedListingModel();

            // init with your API key
            var newsApiClient    = new NewsApiClient("de67b2237afe4fb1b77bfbe773987fca");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = "Trump",
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = new DateTime(2020, 01, 01)
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                foreach (var article in articlesResponse.Articles)
                {
                    feedList.TotalResults = articlesResponse.TotalResults;
                    feedList.Author       = article.Author;
                    feedList.Description  = article.Description;
                    feedList.PublishedAt  = Convert.ToDateTime(article.PublishedAt);
                    feedList.Title        = article.Title;
                    feedList.Url          = article.Url;
                    feedList.UrlToImage   = article.UrlToImage;
                }
            }

            return(feedList);
        }
        private static async Task <IEnumerable <ArticleModel> > GetNews(Dictionary <string, string> state)
        {
            var result   = new List <ArticleModel>();
            var newState = new Dictionary <string, string>();

            foreach (var keyword in state.Keys)
            {
                var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
                {
                    Q        = keyword,
                    SortBy   = SortBys.PublishedAt,
                    Language = Languages.EN,
                    From     = DateTime.Now.Date,
                    PageSize = 100
                });

                result.AddRange(articlesResponse
                                .Articles
                                .TakeWhile(a => a.Title != state[keyword])
                                .Map(keyword)
                                .ToList());

                if (articlesResponse.Articles.Any())
                {
                    newState[keyword] = articlesResponse.Articles.First().Title;
                }
            }

            foreach (var key in newState.Keys)
            {
                state[key] = newState[key];
            }

            return(result);
        }
Esempio n. 8
0
        public void getNews()
        {
            // init with your API key
            var newsApiClient    = new NewsApiClient("81e27dad45464fc3a21aa17d61f3e3b1");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = "Apple",
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = new DateTime(2018, 1, 25)
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                // total results found
                Console.WriteLine(articlesResponse.TotalResults);
                // here's the first 20
                foreach (var article in articlesResponse.Articles)
                {
                    // title
                    Console.WriteLine(article.Title);
                    // author
                    Console.WriteLine(article.Author);
                    // description
                    Console.WriteLine(article.Description);
                    // url
                    Console.WriteLine(article.Url);
                    // image
                    Console.WriteLine(article.UrlToImage);
                    // published at
                    Console.WriteLine(article.PublishedAt);
                }
            }
            Console.ReadLine();
        }
Esempio n. 9
0
        public IActionResult GetNewsApi(string SearchTerm)
        {
            var newsApiClient    = new NewsApiClient(NewsApiKey);
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = SearchTerm,
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = new DateTime(2019, 10, 5)
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                // total results found
                Console.WriteLine(articlesResponse.TotalResults);
                // here's the first 20
                foreach (var article in articlesResponse.Articles)
                {
                    // title
                    Console.WriteLine(article.Title);
                    // author
                    Console.WriteLine(article.Author);
                    // description
                    Console.WriteLine(article.Description);
                    // url
                    Console.WriteLine(article.Url);
                    // image
                    Console.WriteLine(article.UrlToImage);
                    // published at
                    Console.WriteLine(article.PublishedAt);
                }
            }
            return(Ok(articlesResponse));
        }
Esempio n. 10
0
        public ArticlesResult GetEverything()
        {
            var everythingRequest = new EverythingRequest();

            var articlesResult = _client.GetEverything(everythingRequest);

            return(articlesResult);
        }
        public void GetNews(object sender = null, ElapsedEventArgs e = null)
        {
            List <NewsAPI.Models.Article> newNews = new List <NewsAPI.Models.Article>();

            try
            {
                var newsApiClient = new NewsApiClient(apiKey);

                var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
                {
                    Q        = "all",
                    SortBy   = SortBys.PublishedAt,
                    Language = Languages.RU,
                    From     = DateTime.Now - TimeSpan.FromDays(1)
                });

                if (articlesResponse.Status == Statuses.Ok)
                {
                    DateTime latestArticle = DateTime.MinValue;
                    if (Articles.Count > 0 && Articles[0].PublishedAt.HasValue)
                    {
                        latestArticle = Articles[0].PublishedAt.Value;
                    }


                    foreach (var article in articlesResponse.Articles)
                    {
                        if (article.PublishedAt.HasValue && article.PublishedAt.Value > latestArticle)
                        {
                            Articles.Add(article);
                            newNews.Add(article);
                        }
                    }
                }
                else
                {
                    Console.WriteLine(articlesResponse.Error.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                foreach (var art in newNews)
                {
                    /*Console.WriteLine(art.Title);
                     * Console.WriteLine(article.Author);
                     * Console.WriteLine(article.Description);
                     * Console.WriteLine(article.Url);
                     * Console.WriteLine(article.UrlToImage);
                     * Console.WriteLine(article.PublishedAt);*/
                    NewsReceived(new MessageSendServe.Article(art.Title, art.Description, art.PublishedAt.ToString()));
                }
            }
        }
Esempio n. 12
0
        public static List <MultiLanguageInput> GetNewsNewsApi(ref string news, string q)
        {
            // init with your API key
            var newsApiClient = new NewsApiClient("288e5576cf624fec9fed057fc290fb29");


            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q = q,

                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = DateTime.Today.AddDays(0)
            });
            List <MultiLanguageInput> result = new List <MultiLanguageInput>();

            news = "<table><tr><td>ID</td><td>News Title</td><td>News URL</td></tr>";
            string[] strToReplace = new string[] { "USD/JPY", "USD-JPY" };
            if (articlesResponse.Status == Statuses.Ok)
            {
                // total results found
                Console.WriteLine(articlesResponse.TotalResults);
                int i = 0;
                // here's the first 20
                foreach (var article in articlesResponse.Articles)
                {
                    // title
                    Console.WriteLine(article.Title);
                    news += "<tr>";
                    // author
                    Console.WriteLine(article.Author);
                    // description
                    Console.WriteLine(article.Description);
                    // url
                    Console.WriteLine(article.Url);
                    // image
                    Console.WriteLine(article.UrlToImage);
                    // published at
                    Console.WriteLine(article.PublishedAt);

                    string articleStr = "";
                    foreach (string str in strToReplace)
                    {
                        articleStr = CleanUpTitle(article.Description, str, q);
                    }
                    result.Add(new MultiLanguageInput("en", i.ToString(), articleStr));
                    news += "<td>" + (i + 1) + "</td>";
                    news += "<td>" + article.Title + "</td>";
                    news += "<td>" + article.Url + "</td>";
                    news += "</tr>";
                    i++;
                }
                news += "</table>";
            }
            return(result);
        }
Esempio n. 13
0
        public ActionResult Index(NewsFeed news)
        {
            var mvcName = typeof(Controller).Assembly.GetName();
            var isMono  = Type.GetType("Mono.Runtime") != null;

            ViewData["Version"] = mvcName.Version.Major + "." + mvcName.Version.Minor;
            ViewData["Runtime"] = isMono ? "Mono" : ".NET";

            var newsApiClient    = new NewsApiClient("cb0c01ef96964a42a903295d3fce7aa0");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = "Google",
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = new DateTime(2018, 1, 25)
            });

            IList <NewsFeed> articleList = new List <NewsFeed>();

            if (articlesResponse.Status == Statuses.Ok)
            {
                // total results found
                Console.WriteLine(articlesResponse.TotalResults);
            }

            // here's the first 20
            foreach (var article in articlesResponse.Articles)
            {
                NewsFeed LatestNews = new NewsFeed();
                {
                    // title
                    LatestNews.Title = article.Title;
                    // author
                    LatestNews.Author = article.Author;
                    // description
                    LatestNews.Description = article.Description;
                    // url
                    LatestNews.Url = article.Url;
                    // image
                    LatestNews.UrlToImage = article.UrlToImage;
                    // published at
                    LatestNews.PublishedAt = article.PublishedAt;
                };

                articleList.Add(LatestNews);

                var list = new List <NewsFeed>(articleList);

                news.NewsList = list;
            }

            return(View(news));
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            // init with your API key
            var newsApiClient = new NewsApiClient("81c072dd1ec540069da4d4069ce99f39");
            int hitsperpage   = 80;
            int i             = 2;
            int j             = 1;
            int tot_arts      = 300;

            while (i <= tot_arts / hitsperpage)
            {
                var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
                {
                    Q        = "Bitcoin",
                    SortBy   = SortBys.Popularity,
                    Language = Languages.EN,
                    From     = new DateTime(2020, 4, 1),
                    PageSize = hitsperpage,
                    Page     = i
                });

                if (articlesResponse.Status == Statuses.Ok)
                {
                    // total results found
                    tot_arts = articlesResponse.TotalResults;
                    int start = (i - 1) * 100 + 1;
                    int end   = start + 99;
                    Console.WriteLine(String.Format("Articles {0}-{1} of {2}", start, end, tot_arts));
                    foreach (var article in articlesResponse.Articles)
                    {
                        // title
                        Console.WriteLine(j.ToString(), article.Title);
                        // url
                        Console.WriteLine(article.Url);
                        // published at
                        Console.WriteLine(article.PublishedAt);

                        if (article.Author != null && article.Description != null && article.PublishedAt != null && article.Title != null)
                        {
                            // Convert to unixtime
                            long unixtime = ((DateTimeOffset)article.PublishedAt).ToUnixTimeSeconds();
                            DataAccess.InsertNews((DateTime)article.PublishedAt, unixtime, article.Url, article.Title, article.Author, article.Description);
                            j++;
                        }
                    }
                }
                Thread.Sleep(3000);
                i++;
            }
            Console.ReadLine();
        }
Esempio n. 15
0
        public void BadEverythingRequestReturnsError()
        {
            var everythingRequest = new EverythingRequest
            {
                Q = "bitcoin"
            };

            var brokenClient = new NewsApiClient("nokey");

            var result = brokenClient.GetEverything(everythingRequest);

            Assert.Equal(Statuses.Error, result.Status);
            Assert.Null(result.Articles);
            Assert.NotNull(result.Error);
            Assert.Equal(ErrorCodes.ApiKeyInvalid, result.Error.Code);
        }
Esempio n. 16
0
        static void GetNews(string query)
        {
            // init with your API key
            var newsApiClient    = new NewsApiClient("fa75cbab0d584c0cb5b189238c6ba5de");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = query,
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = new DateTime(
                    2019,
                    11,
                    3)
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                // total results found
                Console.WriteLine("Articles Found: " + articlesResponse.TotalResults);
                Console.WriteLine("First 20:");

                // here's the first 20
                foreach (var article in articlesResponse.Articles)
                {
                    // title
                    Console.WriteLine(article.Title);
                    Console.WriteLine("\r\n");
                    // author
                    Console.WriteLine(article.Author);
                    Console.WriteLine("\r\n");
                    // description
                    Console.WriteLine(article.Description);
                    Console.WriteLine("\r\n");
                    Console.WriteLine("\r\n");
                    // url
                    Console.WriteLine(article.Url);
                    // image
                    Console.WriteLine(article.UrlToImage);
                    // published at
                    Console.WriteLine(article.PublishedAt);
                    Console.WriteLine("\r\n" + "\r\n");
                    Console.WriteLine("\r\n");
                    Console.WriteLine("Press enter to continue...");
                    Console.ReadLine();
                }
            }
        }
Esempio n. 17
0
        public IActionResult Results(string searchTerm)
        {
            var           newsApiClient  = new NewsApiClient("0fd2bcfa9ab24fdb97eb9f05847f01a9");
            List <string> articleList    = new List <string>();
            int           relevantCount  = 0;
            int           thisMonthCount = 0;

            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = searchTerm,
                SortBy   = SortBys.Relevancy,
                Language = Languages.EN,
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                if (articlesResponse.TotalResults > 0)
                {
                    foreach (var article in articlesResponse.Articles)
                    {
                        articleList.Add(article.Title + " " + article.PublishedAt.Value.ToShortDateString() + " @! " + article.Url);


                        if (article.Title.Contains(searchTerm.Split(" ")[0]))
                        {
                            relevantCount++;
                        }

                        if (article.PublishedAt.Value.Month == DateTime.Today.Month)
                        {
                            thisMonthCount++;
                        }
                    }
                }
                else
                {
                    articleList.Add("No results found for this virus.");
                }
            }

            ViewData["searchResultsCount"] = articlesResponse.TotalResults;
            ViewData["searchTerm"]         = searchTerm;
            ViewData["relevantCount"]      = relevantCount;
            ViewData["thisMonthCount"]     = thisMonthCount;

            return(View(articleList));
        }
Esempio n. 18
0
        public JsonResult GetJson()
        {
            var newsApiClient    = new NewsApiClient("e43bd86cba4e44c9953fbc0e959cfab3");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = "bbc-sport",
                SortBy   = SortBys.Popularity,
                Language = Languages.EN
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                string json = JsonConvert.SerializeObject(articlesResponse);
                return(Json(articlesResponse));
            }
            return(Json(articlesResponse));
        }
Esempio n. 19
0
        public void TurkeyNewsConn()
        {
            // init with your API key
            var newsApiClient    = new NewsApiClient("acffc7a435f24838a883e692c0fa44dc");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                // Q = "Apple",
                SortBy   = SortBys.PublishedAt,
                Language = Languages.TR,
                //From = new DateTime(2018, 1, 25)
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                var result = articlesResponse.Articles;
            }
        }
Esempio n. 20
0
        private async Task <bool> QueryNewsApiEverything(int pageSize)
        {
            var response = new ArticlesResult();

            _logger.Info("Querying NewsApi. Page: " + _newsApiPage);

            await Task.Run(() => response = _newsApiClient.GetEverything(new EverythingRequest
            {
                Sources = _newsApiSourceRepository.GetAll(new DateTime(2018, 1, 1), 0).Select(c => c.ApiSourceName).ToList(), //get from db
                SortBy  = SortBys.Popularity,
                //Language = Languages.EN,
                From     = DateTime.Now.AddMinutes(-30),
                PageSize = pageSize,
                //Country = _newsApiCountry,
                Page = _newsApiPage
            }));

            if (response.Status == Statuses.Ok)
            {
                _resultsRemaining = response.TotalResults - (_newsApiPage * pageSize);

                foreach (var a in response.Articles)
                {
                    var article = new NewsArticle
                    {
                        Headline        = a.Title,
                        SourceId        = 1,
                        NewsApiSourceId = a.Source.Id,
                        Description     = a.Description,
                        IsVisible       = true,
                        ImageUrl        = a.UrlToImage,
                        Url             = a.Url,
                        CreatedOn       = DateTime.Now,
                        PublishedOn     = a.PublishedAt.HasValue ? a.PublishedAt.Value : DateTime.Now
                    };

                    _logger.Info("Adding article: " + a.Title + " from Source " + a.Source.Name);

                    _newsArticles.Add(article);
                }

                return(true);
            }

            return(false);
        }
        public IActionResult Index(ArticlesResult articlesResult)
        {
            //Use appsettings.json to change api url and key
            var newsApiClient = new NewsApiClient(_appSettings.NewsApiKey, _appSettings.NewsApiUrl);

            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Sources  = { "the-new-york-times" },
                Q        = "Apple",
                SortBy   = SortBys.PublishedAt,
                Language = Languages.EN,
                From     = new DateTime(2018, 09, 24)
            });


            return(View(articlesResponse));
        }
Esempio n. 22
0
        public IActionResult MainMediaPage()
        {
            //Date Time to get current day
            DateTime dateNow = DateTime.Today;

            var newsApiClient    = new NewsApiClient("");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = "Technology",
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                //Add DateNow.addDays to subtract month value so always current
                From     = dateNow.AddDays(-30),
                PageSize = 9
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                return(View(articlesResponse.Articles));

                // Code below was changed to return the view above as a bag model, this was API standard

                /*
                 * // total results found
                 * Console.WriteLine(articlesResponse.TotalResults);
                 * // here's the first 20
                 * foreach (var article in articlesResponse.Articles)
                 * {
                 *  // title
                 *  Console.WriteLine(article.Title);
                 *  // author
                 *  Console.WriteLine(article.Author);
                 *  // description
                 *  Console.WriteLine(article.Description);
                 *  // url
                 *  Console.WriteLine(article.Url);
                 *  // published at
                 *  Console.WriteLine(article.PublishedAt);
                 * }*/
            }
            //Console.ReadLine();


            return(View());
        }
        public void NewsApiFunctionTestFjaleKyceSakte()
        {
            //Arrange
            Mock <IDataManager> moqdm = new Mock <IDataManager>();
            DataSet             ds    = new DataSet();
            DataTable           dt    = new DataTable("MyTable");

            dt.Columns.Add(new DataColumn("Emer", typeof(string)));
            dt.Columns.Add(new DataColumn("Email", typeof(string)));
            dt.Columns.Add(new DataColumn("TipiAbonimi", typeof(string)));
            dt.Columns.Add(new DataColumn("NjoftimFundit", typeof(DateTime)));
            DataRow dr = dt.NewRow();

            dr["Emer"]          = "user1";
            dr["Email"]         = "email1";
            dr["TipiAbonimi"]   = "fjale";
            dr["NjoftimFundit"] = "2019-10-17";
            dt.Rows.Add(dr);
            ds.Tables.Add(dt);
            var fjala         = "Samsung , Apple";        //beje vetem samsung per te bere fail
            var newsApiClient = new NewsApiClient("key"); //vendosi nje vlere tjeter per fail

            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = fjala,
                Language = Languages.EN
            });

            moqdm.Setup(x => x.getEntity()).Returns(ds);
            var rez = moqdm.Object.getEntity();

            DateTime.TryParse(ds.Tables[0].Rows[0].ItemArray.GetValue(3).ToString(), out DateTime njoftimi);
            foreach (var article in articlesResponse.Articles)
            {
                //Assert
                Assert.AreEqual(fjala.ToLower().Contains(","), true);
                Assert.AreEqual(ds.Tables[0].Rows.Count, rez.Tables[0].Rows.Count);
                Assert.IsTrue(article.PublishedAt > njoftimi);
                Assert.AreEqual(Statuses.Ok, articlesResponse.Status);
                Assert.IsTrue(articlesResponse.TotalResults > 0);
                Assert.IsTrue(articlesResponse.Articles.Count > 0);
                Assert.IsNull(articlesResponse.Error);
                moqdm.Verify(x => x.getEntity(), Times.Once());
            }
        }
Esempio n. 24
0
        ///Returns list of Articles

        public static ArticlesResult GetEverything(EverythingRequest reqParams)
        {
            try {
                var newsApiClient = new NewsApiClient(apiKey);
                var articleresult = newsApiClient.GetEverything(reqParams);
                if (articleresult.Status == Statuses.Ok)
                {
                    return(articleresult);
                }
                else
                {
                    throw new ApiResponseException(articleresult.Error.Message);
                }
            } catch (AggregateException e)
            {
                throw new ApiResponseException(e.Message);
            }
        }
Esempio n. 25
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                //ConsolaPruebaAPI.Program execMain = new Program();
                //execMain.Main(string args);



                var newsApiClient = new NewsApiClient("a55ecdd5ddd34f279b3b9e1ffd1eefa9");

                var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
                {
                    Q        = "La casa de papel",
                    SortBy   = SortBys.Popularity,
                    Language = Languages.ES,
                    From     = new DateTime(2018, 6, 13),
                    PageSize = 1
                });
                if (articlesResponse.Status == Statuses.Ok)
                {
                    // total results found
                    Label1.Text = articlesResponse.TotalResults.ToString();
                    // here's the first 20
                    foreach (var article in articlesResponse.Articles)
                    {
                        // title
                        Label1.Text = article.Title;
                        //Label1.Text = article.Author;
                        //Label1.Text = article.Description;
                        //Label1.Text = article.Url;
                        //Label1.Text = article.UrlToImage;
                        //Label1.Text = article.PublishedAt.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Label1.Text = ex.Message;
            }
        }
Esempio n. 26
0
    public string getNews(string keyword)
    {
        var newsApiClient    = new NewsApiClient("09f77db57ec44cdea52164d405a1bbba");
        var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
        {
            Q        = keyword,
            SortBy   = SortBys.Popularity,
            Language = Languages.EN,
        });
        StringBuilder result = new StringBuilder();

        if (articlesResponse.Status == Statuses.Ok)
        {
            foreach (var article in articlesResponse.Articles)
            {
                result.Append("News Title: " + article.Title);
                result.Append(Environment.NewLine);
                result.Append("URL: " + article.Url + Environment.NewLine);
            }
        }
        return(result.ToString());
    }
        public IActionResult Index(string id)
        {
            var News = new NewsViewModel();
            var dir  = @"/images/" + id.Replace(" ", "_") + @"/" + id.Replace(" ", "_");

            News.img1  = dir + "1.png";
            News.img2  = dir + "2.png";
            News.img3  = dir + "3.png";
            News.img4  = dir + "4.png";
            News.dt    = Convert.ToDateTime(System.IO.File.ReadAllText(Environment.CurrentDirectory + @"\wwwroot\images\" + id.Replace(" ", "_") + @"\" + "date.txt"));
            News.coeff = System.IO.File.ReadAllText(Environment.CurrentDirectory + @"\wwwroot\images\" + id.Replace(" ", "_") + @"\" + "res.txt");
            var news             = new List <PieceOfNews>();
            var newsApiClient    = new NewsApiClient("c4cdf6d372ae4e6badf36a0851ba882c");
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = id.Replace(" ", "+"),
                SortBy   = SortBys.Relevancy,
                Language = Languages.EN,
                PageSize = 5,
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                foreach (var article in articlesResponse.Articles)
                {
                    var currentPoN = new PieceOfNews {
                        title       = article.Title,
                        author      = article.Author,
                        description = article.Description,
                        url         = article.Url,
                        publishedAt = article.PublishedAt,
                    };
                    news.Add(currentPoN);
                }
            }
            News.News = news;

            return(View(News));
        }
Esempio n. 28
0
        public static List <NewsInfo> GetNews()
        {
            List <NewsInfo> articleList = new List <NewsInfo>();

            List <string> sources = new List <string>(new string[] { "bloomberg,financial-times,fortune,financial-post,the-wall-street-journal" });

            var keys = new Keys();
            // init with your API key
            var newsApiClient    = new NewsApiClient(keys.APIKey);
            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                // Q = "business",
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                PageSize = 10,
                Sources  = sources,
                From     = DateTime.Now.AddDays(-1)
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                foreach (var article in articlesResponse.Articles)
                {
                    articleList.Add(new NewsInfo()
                    {
                        Title         = article.Title,
                        Author        = article.Author,
                        Source        = article.Source.Name,
                        Description   = article.Description,
                        Url           = article.Url,
                        ImageUrl      = article.UrlToImage,
                        DatePublished = article.PublishedAt.ToString()
                    });
                }
            }
            return(articleList);
        }
Esempio n. 29
0
        public List <ArticleResponse> GetNews(string searchPhrase)
        {
            var articlesResponse = _newsApiClient.GetEverything(new EverythingRequest
            {
                Q        = string.Join(" OR ", searchPhrase.Split(" ")),
                SortBy   = SortBys.Popularity,
                Language = Languages.EN,
                From     = DateTime.Now.AddDays(-1),
                PageSize = 100,
            });

            if (articlesResponse.Status != Statuses.Ok)
            {
                _logger.LogError($"Failed to fetch News, Error {articlesResponse.Error.Message}");
                return(null);
            }

            _logger.LogInformation($"Fetched {articlesResponse.TotalResults} articles with phrase {searchPhrase}");

            return(articlesResponse.Articles.Select(x => new ArticleResponse()
            {
                Title = x.Title, Url = x.Url
            }).ToList());
        }
        public IActionResult Index(string state, int page = 1)
        {
            var vehicles = vehicleRepo.Vehicles;

            if (state == "nya")
            {
                vehicles = vehicles.Where(s =>
                                          s.Used is false);
            }

            if (state == "begagnade")
            {
                vehicles = vehicles.Where(s =>
                                          s.Used is true);
            }

            // Generate a list with the BrandId of cars in stock and place in the viewmodel further down

            List <Brand> brandsInStock = new List <Brand>();

            foreach (var v in vehicles)
            {
                if (!brandsInStock.Contains(v.Brand))
                {
                    brandsInStock.Add(v.Brand);
                }
            }

            var toSkip = (page - 1) * PageLimit;
            var vehiclesInPageLimit = vehicles
                                      .OrderBy(x => x.Id)
                                      .Skip(toSkip)
                                      .Take(PageLimit);

            var totalNumberOfVehicles = vehicles.Count();

            var showButton = true;

            if (page * PageLimit > totalNumberOfVehicles)
            {
                showButton = false;
            }

            var newsApiClient = new NewsApiClient(_appSettings.NewsApiKey, _appSettings.NewsApiUrl);

            var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
            {
                Sources  = { "the-new-york-times" },
                Q        = "Apple",
                SortBy   = SortBys.PublishedAt,
                Language = Languages.EN,
                From     = new DateTime(2018, 09, 24)
            });

            var vm = new VehicleListViewModel
            {
                Vehicles        = vehiclesInPageLimit,
                BrandsInStock   = brandsInStock,
                ShowButton      = showButton,
                NextPage        = ++page,
                ArticlesResults = articlesResponse
            };

            return(View(vm));
        }