public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            var apiKeys = new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("NewsSearchApiKey"));

            var newsClient = new NewsSearchClient(apiKeys)
            {
                Endpoint = Environment.GetEnvironmentVariable("NewsSearchUrl")
            };

            var returnArticles = new List <PartlyNewsy.Models.Article>();

            var news = await newsClient.News.SearchAsync(query : "");

            foreach (var item in news.Value)
            {
                var article = new PartlyNewsy.Models.Article {
                    ArticleUrl           = item.Url,
                    Category             = item.Category,
                    DatePublished        = DateTime.Parse(item.DatePublished),
                    FeaturedImage        = item.Image.Thumbnail.ContentUrl,
                    Headline             = item.Name,
                    NewsProviderImageUrl = item.Provider.First().Image.Thumbnail.ContentUrl,
                    NewsProviderName     = item.Provider.First().Name
                };

                returnArticles.Add(article);
            }

            return(new OkObjectResult(returnArticles));
        }
        static void Main(string[] args)
        {
            var key        = "xyx";
            var searchTerm = "Human resource updates";

            var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));

            var newsResults = client.News.SearchAsync(query: searchTerm, market: "en-us", count: 10).Result;

            if (newsResults.Value.Count > 0)
            {
                var firstNewsResult = newsResults.Value[0];

                Console.WriteLine($"TotalEstimatedMatches value: {newsResults.TotalEstimatedMatches}");
                Console.WriteLine($"News result count: {newsResults.Value.Count}");
                Console.WriteLine($"First news name: {firstNewsResult.Name}");
                Console.WriteLine($"First news url: {firstNewsResult.Url}");
                Console.WriteLine($"First news description: {firstNewsResult.Description}");
                Console.WriteLine($"First news published time: {firstNewsResult.DatePublished}");
                Console.WriteLine($"First news provider: {firstNewsResult.Provider[0].Name}");
            }

            else
            {
                Console.WriteLine("Couldn't find news results!");
            }
            Console.WriteLine("Enter any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 3
0
        public BingNewsService()
        {
            ApiKeyServiceClientCredentials creds = new ApiKeyServiceClientCredentials(bingAPIKey);

            searchClient = new NewsSearchClient(creds)
            {
                Endpoint = bingUrl
            };
        }
Exemplo n.º 4
0
        public NewsClient(string endPoint, string key)
        {
            _client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key), new HttpUrlRewriteHandler());

            if (!string.IsNullOrEmpty(endPoint))
            {
                _client.Endpoint = endPoint;
            }
        }
Exemplo n.º 5
0
        public async Task CreateNewsObjectsFromSearch(MessageObject <ShowObject> message, ILogger log, int count)
        {
            //Leverage the Cognitive Services Bing Search API and log out the action
            INewsSearchClient client = new NewsSearchClient(new NewsApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("bingSearchSubscriptionKey")));

            log.LogInformation($"[Request Correlation ID: {message.Headers.RequestCorrelationId}] :: Searching for associated images");
            Microsoft.Azure.CognitiveServices.Search.NewsSearch.Models.News newsResults = client.News.SearchAsync(query: $"{message.Body.ShowName} (Musical)", count: count).Result;

            //Initialise a temporaryObject and loop through the results
            //For each result, create a new NewsObject which has a condensed set
            //of properties, for storage in CosmosDB in line with the show data model
            //Once looped through send an OK Result
            //TODO: There is definitely a better way of doing this, but got a rough working approach out
            MessageObject <NewsObject> _object = new MessageObject <NewsObject>()
            {
                Body    = null,
                Headers = new MessageHeaders()
                {
                    RequestCorrelationId = message.Headers.RequestCorrelationId,
                    RequestCreatedAt     = DateTime.Now
                }
            };

            foreach (Microsoft.Azure.CognitiveServices.Search.NewsSearch.Models.NewsArticle newsItem in newsResults.Value)
            {
                try
                {
                    _object.Body = new NewsObject()
                    {
                        Id            = Guid.NewGuid().ToString(),
                        BingId        = newsItem.BingId,
                        DatePublished = newsItem.DatePublished,
                        Name          = newsItem.Name,
                        Url           = newsItem.Url,
                        CreatedAt     = DateTime.Now,
                        Doctype       = DocTypes.News,
                        Partition     = message.Body.Partition
                    };

                    await _dataLayer.CreateNewsAsync(_object);

                    log.LogInformation($"[Request Correlation ID: {message.Headers.RequestCorrelationId}] :: News Article Creation Success :: Image ID: {_object.Body.BingId} ");
                }
                catch (Exception ex)
                {
                    log.LogInformation($"[Request Correlation ID: {message.Headers.RequestCorrelationId}] :: News Article Creation Fail ::  :: Image ID: {_object.Body.BingId} - {ex.Message}");
                }
            }
        }
        public void GetNewsTest()
        {
            var request = new NewsSearchRequest();

            request.Query      = "unicorns";
            request.Count      = 10;
            request.Offset     = 0;
            request.Market     = "en-US";
            request.SafeSearch = SafeSearch.Moderate;

            var client = new NewsSearchClient(this.apiKey);

            var response = client.GetNews(request);

            Assert.IsTrue(response.Results.Count > 0);
        }
        public override async Task <bool?> ShouldBuyStock(StockInput newData)
        {
            if (!_lastCallTime.HasValue || _lastCallTime < DateTime.Now.AddDays(-1))
            {
                var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(_config.News_Search_Api_Key))
                {
                    Endpoint = _config.News_Search_Endpoint
                };

                var result = await client.News.SearchAsync(query : newData.StockSymbol, market : "en-US", freshness : "Day", count : 100);

                return(false);
            }
            else
            {
                return(_lastReturn);
            }
        }
        public async Task DoStuff()
        {
            var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(_config.News_Search_Api_Key))
            {
                Endpoint = _config.News_Search_Endpoint
            };

            using var tw = new StreamWriter("SavedList.txt");

            for (int i = 0; i < 10; i++)
            {
                var result = await client.News.CategoryAsync(market : "en-US", count : 100, category : "Business", offset : 100 *i);

                foreach (string s in result.Value.Select(x => x.Name))
                {
                    tw.WriteLine(s);
                }
            }
        }
Exemplo n.º 9
0
        public static List <NewsObject> NewsSearchWithFilters(string subscriptionKey, string query)
        {
            List <NewsObject> news = new List <NewsObject>();

            var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var newsResults = client.News.SearchAsync(query: query, market: "en-us", freshness: "Week", sortBy: "Date").Result;
                //Console.WriteLine("Search most recent news for query with freshness and sortBy");

                if (newsResults == null)
                {
                    //Console.WriteLine("Didn't see any news result data..");
                }
                else
                {
                    if (newsResults.Value.Count > 0)
                    {
                        foreach (var firstNewsResult in newsResults.Value)
                        {
                            news.Add(new NewsObject()
                            {
                                Name = firstNewsResult.Name, Url = firstNewsResult.Url
                            });
                        }
                    }
                    else
                    {
                        //Console.WriteLine("Couldn't find news results!");
                    }
                }
            }

            catch (Exception ex)
            {
                //Console.WriteLine("Encountered exception. " + ex.Message);
            }

            return(news);
        }
Exemplo n.º 10
0
        private async Task <List <News> > GetNews(string destination)
        {
            try
            {
                var client = new NewsSearchClient(new Microsoft.Azure.CognitiveServices.Search.NewsSearch.ApiKeyServiceClientCredentials(ApiKeys.BingImageSearch));

                var resultNews = new List <News>();

                var result = await client.News.SearchAsync(destination);

                int currentResult = 0;
                while (currentResult < 5 || result.Value.Count < currentResult)
                {
                    resultNews.Add(new News()
                    {
                        Title       = result.Value[currentResult].Name,
                        Description = result.Value[currentResult].Description,
                        ImageUrl    = result.Value[currentResult].Image.Thumbnail.ContentUrl,
                        MoreInfoUrl = result.Value[currentResult].Url
                    });

                    currentResult++;
                }

                return(resultNews);
            }
            catch
            {
                return(new List <News> {
                    new News
                    {
                        Title = "Something went wrong :( Here is a cat instead!",
                        ImageUrl = "https://cataas.com/cat",
                        MoreInfoUrl = "https://cataas.com/"
                    }
                });
            }
        }
Exemplo n.º 11
0
        public void NewsSearch()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "NewsSearch");

                INewsSearchClient client = new NewsSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance());

                var resp = client.News.SearchAsync(query: "tom cruise").Result;

                Assert.NotNull(resp);
                Assert.NotNull(resp.Value);
                Assert.True(resp.Value.Count > 0);

                var news = resp.Value[0];
                Assert.NotNull(news.Name);
                Assert.NotNull(news.Url);
                Assert.NotNull(news.Description);
                Assert.NotNull(news.DatePublished);
                Assert.NotNull(news.Provider);
                Assert.NotNull(news.Provider[0].Name);
            }
        }
Exemplo n.º 12
0
        public void NewsTrending()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "NewsTrending");

                INewsSearchClient client = new NewsSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance());

                var resp = client.News.TrendingAsync().Result;

                Assert.NotNull(resp);
                Assert.NotNull(resp.Value);
                Assert.True(resp.Value.Count > 0);

                var trendingTopic = resp.Value[0];
                Assert.NotNull(trendingTopic.Name);
                Assert.NotNull(trendingTopic.WebSearchUrl);
                Assert.NotNull(trendingTopic.NewsSearchUrl);
                Assert.NotNull(trendingTopic.Image);
                Assert.NotNull(trendingTopic.Image.Url);
                Assert.NotNull(trendingTopic.Query);
                Assert.NotNull(trendingTopic.Query.Text);
            }
        }
Exemplo n.º 13
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var allTheNewsThatsFitToPrint = new List <PartlyNewsy.Models.Article>();

            string requestBody        = await new StreamReader(req.Body).ReadToEndAsync();
            var    favoriteCategories = JsonConvert.DeserializeObject <List <string> >(requestBody);

            var creds      = new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("NewsSearchKey"));
            var newsClient = new NewsSearchClient(creds)
            {
                Endpoint = Environment.GetEnvironmentVariable("BingNewsSearchEndpointUrl")
            };

            List <News> theNews = new List <News>();

            try
            {
                foreach (var category in favoriteCategories)
                {
                    var newsForCategory = await newsClient.News.CategoryAsync(category : category);

                    theNews.Add(newsForCategory);
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            try
            {
                int articleCounter            = 0;
                List <NewsArticle> newsToLoop = new List <NewsArticle>();

                foreach (var newsItem in theNews)
                {
                    newsToLoop.AddRange(newsItem.Value.Take(2));
                }

                var shuffled = ShuffleList(newsToLoop.ToList());

                foreach (var article in shuffled)
                {
                    try
                    {
                        allTheNewsThatsFitToPrint.Add(
                            new Models.Article
                        {
                            FeaturedImage        = article.Image.Thumbnail.ContentUrl.Replace("&pid=News", string.Empty),
                            ImageUrl             = article.Image.Thumbnail.ContentUrl.Replace("&pid=News", string.Empty),
                            NewsProviderName     = article.Provider.FirstOrDefault()?.Name,
                            Headline             = article.Name,
                            NewsProviderImageUrl = article.Provider.FirstOrDefault()?.Image?.Thumbnail?.ContentUrl.Replace("&pid=News", String.Empty),
                            Category             = article.Category,
                            DatePublished        = DateTime.Parse(article.DatePublished),
                            CurrentArticleCount  = articleCounter,
                            ArticleUrl           = article.Url
                        }
                            );

                        articleCounter += 1;
                    } catch (NullReferenceException)
                    {
                        // just skip this item if we run into a null reference
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            return(new OkObjectResult(allTheNewsThatsFitToPrint));
        }
Exemplo n.º 14
0
 public NewsImplementation()
 {
     client          = new NewsSearchClient(new ApiKeyServiceClientCredentials("4fa7760d760f43c193545adc6c28f4cc"));
     client.Endpoint = "https://api.cognitive.microsoft.com/";
 }
Exemplo n.º 15
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string locality = req.Query["locality"];

            var allTheNewsThatsFitToPrint = new List <PartlyNewsy.Models.Article>();

            var creds      = new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("NewsSearchApiKey"));
            var newsClient = new NewsSearchClient(creds)
            {
                Endpoint = Environment.GetEnvironmentVariable("NewsSearchUrl")
            };

            News localNews = null;

            try
            {
                localNews = await newsClient.News.SearchAsync(query : locality);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Error during GetNewsByCategory - Calling news");
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            try
            {
                int articleCounter = 0;
                foreach (var article in localNews.Value)
                {
                    try
                    {
                        allTheNewsThatsFitToPrint.Add(
                            new PartlyNewsy.Models.Article
                        {
                            FeaturedImage        = article.Image.Thumbnail.ContentUrl.Replace("&pid=News", string.Empty),
                            NewsProviderName     = article.Provider.FirstOrDefault()?.Name,
                            Headline             = article.Name,
                            NewsProviderImageUrl = article.Provider.FirstOrDefault()?.Image?.Thumbnail?.ContentUrl.Replace("&pid=News", String.Empty),
                            Category             = article.Category,
                            DatePublished        = DateTime.Parse(article.DatePublished),
                            CurrentArticleCount  = articleCounter,
                            ArticleUrl           = article.Url
                        }
                            );

                        articleCounter += 1;
                    }
                    catch (NullReferenceException nre)
                    {
                        log.LogError(nre, "Error during GetNewsByCategory - NullReferenceException");
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Error during GetNewsByCategory");
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            return(new OkObjectResult(allTheNewsThatsFitToPrint));
        }
Exemplo n.º 16
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            var allTheNewsThatsFitToPrint = new List <PartlyNewsy.Models.Article>();

            var creds      = new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("NewsSearchKey"));
            var newsClient = new NewsSearchClient(creds)
            {
                Endpoint = Environment.GetEnvironmentVariable("BingNewsSearchEndpointUrl")
            };

            News topNews = null;

            try
            {
                // Searching w/o a query returns the top news
                topNews = await newsClient.News.SearchAsync(query : "");
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            try
            {
                int articleCounter = 0;
                foreach (var article in topNews.Value)
                {
                    try
                    {
                        allTheNewsThatsFitToPrint.Add(
                            new PartlyNewsy.Models.Article
                        {
                            FeaturedImage        = article.Image.Thumbnail.ContentUrl.Replace("&pid=News", string.Empty),
                            ImageUrl             = article.Image.Thumbnail.ContentUrl.Replace("&pid=News", string.Empty),
                            NewsProviderName     = article.Provider.FirstOrDefault()?.Name,
                            Headline             = article.Name,
                            NewsProviderImageUrl = article.Provider.FirstOrDefault()?.Image?.Thumbnail?.ContentUrl.Replace("&pid=News", String.Empty),
                            Category             = article.Category,
                            DatePublished        = DateTime.Parse(article.DatePublished),
                            CurrentArticleCount  = articleCounter,
                            ArticleUrl           = article.Url
                        }
                            );

                        articleCounter += 1;
                    } catch (NullReferenceException)
                    {
                        // just skip this item if we run into a null reference
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            return(new OkObjectResult(allTheNewsThatsFitToPrint));
        }
 public NewsClient(string key)
 {
     _client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));
 }
Exemplo n.º 18
0
 public BingNews(string apiKey, CancellationToken ct) : base(ct)
 {
     ApiKey      = apiKey ?? throw new ArgumentNullException("apiKey");
     Client      = new NewsSearchClient(new ApiKeyServiceClientCredentials(ApiKey));
     Initialized = true;
 }